Repository: kaydxh/golang Branch: main Commit: 1e54c62fa5c0 Files: 1959 Total size: 124.4 MB Directory structure: gitextract_tcizrmu1/ ├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── doc/ │ ├── health_check_design.md │ ├── opentelemetry_design.md │ └── rate_limit_design.md ├── doc.go ├── go/ │ ├── archive/ │ │ ├── archive.go │ │ ├── option/ │ │ │ └── file_info.go │ │ └── zip/ │ │ ├── zip.go │ │ └── zip_test.go │ ├── bytes/ │ │ ├── bytes.go │ │ └── bytes_test.go │ ├── client/ │ │ ├── client.go │ │ ├── client.options.go │ │ ├── client_options.go │ │ └── client_test.go │ ├── container/ │ │ ├── heap/ │ │ │ ├── heap.go │ │ │ └── heap_test.go │ │ ├── set/ │ │ │ ├── set.go │ │ │ ├── set.interface.go │ │ │ ├── set_interface_test.go │ │ │ ├── set_string.go │ │ │ ├── set_string_test.go │ │ │ └── set_test.go │ │ └── workqueue/ │ │ ├── queue.go │ │ └── queue_test.go │ ├── context/ │ │ ├── context.go │ │ └── context_test.go │ ├── crypto/ │ │ ├── aes/ │ │ │ ├── aes_cbc.go │ │ │ ├── aes_cbc_test.go │ │ │ └── error.go │ │ ├── md5/ │ │ │ ├── md5.go │ │ │ └── md5_test.go │ │ └── sha256/ │ │ ├── sha256.go │ │ └── sha256_test.go │ ├── doc.go │ ├── encoding/ │ │ ├── base64/ │ │ │ ├── base64.go │ │ │ └── base64_test.go │ │ ├── hash/ │ │ │ ├── hash.go │ │ │ └── hash_test.go │ │ ├── jwt/ │ │ │ ├── jwt.go │ │ │ └── jwt_test.go │ │ └── protojson/ │ │ ├── decode.go │ │ ├── decode.option.go │ │ ├── decode_option.go │ │ ├── encode.go │ │ ├── encode.option.go │ │ ├── encode_option.go │ │ ├── protojson_test.go │ │ └── testdata/ │ │ ├── date.pb.go │ │ └── date.proto │ ├── errors/ │ │ ├── error.code.go │ │ ├── error.grpc.go │ │ ├── errors.go │ │ ├── errors_test.go │ │ └── handler.go │ ├── filesystem/ │ │ ├── filesystem.go │ │ └── mountpoint.go │ ├── flag/ │ │ └── flag.go │ ├── go.mod │ ├── go.sum │ ├── idgen/ │ │ ├── id_gen.go │ │ ├── id_gen_test.go │ │ ├── wk_id_gen.go │ │ └── wk_id_gen_test.go │ ├── io/ │ │ ├── copy.go │ │ ├── copy_darwin.go │ │ ├── copy_linux.go │ │ ├── copy_test.go │ │ ├── io.go │ │ ├── io_test.go │ │ └── testdata/ │ │ ├── dir/ │ │ │ ├── file/ │ │ │ │ └── 1.txt │ │ │ └── hello.text │ │ └── file/ │ │ └── 1.txt │ ├── math/ │ │ ├── exp/ │ │ │ ├── exp.go │ │ │ └── exp_test.go │ │ ├── math.go │ │ ├── math_test.go │ │ └── rand/ │ │ ├── rand.go │ │ └── rand_test.go │ ├── net/ │ │ ├── grpc/ │ │ │ ├── example/ │ │ │ │ ├── data.pb.go │ │ │ │ ├── data.proto │ │ │ │ ├── data.repository.go │ │ │ │ ├── data.repository_test.go │ │ │ │ └── data_grpc.pb.go │ │ │ ├── grpc_client.go │ │ │ ├── grpc_client.option.go │ │ │ ├── grpc_client.repository.factory.go │ │ │ ├── grpc_client.repository.go │ │ │ ├── grpc_client_option.go │ │ │ ├── grpc_client_test.go │ │ │ ├── grpc_stats.handler.go │ │ │ └── ip.go │ │ ├── http/ │ │ │ ├── clone.go │ │ │ ├── example/ │ │ │ │ ├── data.pb.go │ │ │ │ ├── data.proto │ │ │ │ └── http_client.repository_test.go │ │ │ ├── http_client.do.go │ │ │ ├── http_client.go │ │ │ ├── http_client.option.go │ │ │ ├── http_client.repository.factory.go │ │ │ ├── http_client.repository.go │ │ │ ├── http_client_option.go │ │ │ ├── http_client_proxy.go │ │ │ ├── http_client_test.go │ │ │ ├── http_error.go │ │ │ ├── http_handler_chain.option.go │ │ │ ├── http_handler_interceptor.go │ │ │ ├── http_handler_interceptor.option.go │ │ │ ├── http_host_context.go │ │ │ ├── http_proxy_context.go │ │ │ ├── http_request_id.go │ │ │ ├── http_round_trip.go │ │ │ ├── http_transport.go │ │ │ ├── http_transport.host.go │ │ │ ├── http_transport.proxy.go │ │ │ ├── ip.go │ │ │ └── response_writer.go │ │ ├── ip.go │ │ ├── ip_test.go │ │ ├── mac.go │ │ ├── mac_test.go │ │ ├── parse.go │ │ ├── resolver/ │ │ │ ├── build.go │ │ │ ├── build.option.go │ │ │ ├── build_option.go │ │ │ ├── dns/ │ │ │ │ ├── dns_resolver.go │ │ │ │ ├── dns_resolver_builder.option.go │ │ │ │ └── dns_resolver_builder_option.go │ │ │ ├── passthrough/ │ │ │ │ └── passthrough.go │ │ │ ├── register.reslover.go │ │ │ ├── resolve/ │ │ │ │ └── resolve.go │ │ │ ├── resolve.all.option.go │ │ │ ├── resolve.all_option.go │ │ │ ├── resolve.now_option.go │ │ │ ├── resolve.one.option.go │ │ │ ├── resolve.one_option.go │ │ │ ├── resolver.go │ │ │ ├── resolver_test.go │ │ │ ├── target.go │ │ │ └── unix/ │ │ │ └── unix.go │ │ └── url/ │ │ ├── url.go │ │ ├── url.resolve.go │ │ ├── url_codec.go │ │ ├── url_option.go │ │ ├── url_test.go │ │ └── value.go │ ├── os/ │ │ ├── env.go │ │ ├── env_test.go │ │ ├── exec/ │ │ │ ├── exec.go │ │ │ ├── exec.options.go │ │ │ ├── exec_options.go │ │ │ └── exec_test.go │ │ ├── file.go │ │ ├── file_test.go │ │ ├── getwd.go │ │ ├── getwd_test.go │ │ ├── proc.go │ │ ├── proc_darwin.go │ │ ├── proc_linux.go │ │ ├── proc_test.go │ │ ├── remove_file.go │ │ ├── signal_posix.go │ │ ├── term/ │ │ │ └── term.go │ │ ├── value.go │ │ └── value_test.go │ ├── path/ │ │ └── filepath/ │ │ ├── match.go │ │ ├── path.go │ │ └── path_test.go │ ├── reflect/ │ │ ├── array.go │ │ ├── array_test.go │ │ ├── error.go │ │ ├── id.go │ │ ├── struct.go │ │ ├── struct_test.go │ │ ├── truncate.go │ │ ├── truncate_test.go │ │ ├── value.go │ │ └── value_test.go │ ├── runtime/ │ │ ├── extern.go │ │ ├── extern_test.go │ │ ├── function.go │ │ ├── function_test.go │ │ ├── goroutine.go │ │ ├── marshaler/ │ │ │ ├── jsonpb.marshaler.go │ │ │ ├── jsonpb.marshaler.option.go │ │ │ ├── jsonpb.marshaler_option.go │ │ │ └── proto.marshaler.go │ │ ├── meta.data.go │ │ ├── panic.go │ │ ├── panic_test.go │ │ └── stack.go │ ├── slices/ │ │ ├── slices.go │ │ └── slices_test.go │ ├── strconv/ │ │ ├── atoi.go │ │ ├── atoi_test.go │ │ ├── atonum.go │ │ ├── atonum_test.go │ │ └── itoa.go │ ├── strings/ │ │ ├── string_slice.go │ │ ├── string_slice_test.go │ │ ├── strings.go │ │ └── strings_test.go │ ├── sync/ │ │ ├── atomic/ │ │ │ ├── file_lock.go │ │ │ └── file_lock_test.go │ │ ├── cond.go │ │ └── cond_test.go │ ├── syscall/ │ │ ├── disk.go │ │ ├── disk_test.go │ │ ├── memory_darwin.go │ │ ├── memory_linux.go │ │ ├── memory_linux_test.go │ │ ├── rlimit.go │ │ ├── rlimit_test.go │ │ └── syscall.go │ ├── time/ │ │ ├── backoff.go │ │ ├── exponential_backoff.go │ │ ├── exponential_backoff.options.go │ │ ├── exponential_backoff_options.go │ │ ├── exponential_backoff_test.go │ │ ├── exponentialbackeoff_syncmap.go │ │ ├── rate/ │ │ │ ├── rate.go │ │ │ ├── rate_method.go │ │ │ ├── rate_qps.go │ │ │ ├── rate_qps_method.go │ │ │ ├── rate_qps_test.go │ │ │ └── rate_test.go │ │ ├── time.go │ │ ├── time_counter.go │ │ ├── time_counter_test.go │ │ ├── time_test.go │ │ ├── wait.go │ │ └── wait_test.go │ ├── unsafe/ │ │ └── unsafe.go │ └── utils/ │ ├── compare.go │ ├── generics_get.go │ └── generics_get_test.go ├── go.mod ├── go.sum ├── pkg/ │ ├── binlog/ │ │ ├── binlog.archive.go │ │ ├── binlog.go │ │ ├── binlog.option.go │ │ ├── binlog.pb.go │ │ ├── binlog.proto │ │ ├── binlog.yaml │ │ ├── binlog_option.go │ │ ├── binlog_test.go │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── datastore/ │ │ │ ├── data.store.go │ │ │ ├── dbstore/ │ │ │ │ └── db.store.go │ │ │ ├── filestore/ │ │ │ │ └── file.store.go │ │ │ └── message.go │ │ ├── go.mod │ │ └── go.sum │ ├── config/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── go.mod │ │ └── go.sum │ ├── container/ │ │ ├── docker/ │ │ │ └── docker.proto │ │ ├── go.mod │ │ └── go.sum │ ├── crontab/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── crontab.go │ │ ├── crontab.pb.go │ │ ├── crontab.proto │ │ ├── crontab.yaml │ │ ├── crontab_test.go │ │ ├── go.mod │ │ ├── go.sum │ │ └── testdata/ │ │ ├── 1.txt │ │ ├── 2.txt │ │ └── 3.txt │ ├── database/ │ │ ├── db.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── mysql/ │ │ │ ├── config.go │ │ │ ├── config.option.go │ │ │ ├── config_option.go │ │ │ ├── migrate/ │ │ │ │ └── rename_db.sql │ │ │ ├── mysql.go │ │ │ ├── mysql.option.go │ │ │ ├── mysql.pb.go │ │ │ ├── mysql.proto │ │ │ ├── mysql.yaml │ │ │ ├── mysql_operate_test.go │ │ │ ├── mysql_options.go │ │ │ ├── mysql_test.go │ │ │ ├── mysql_transaction.go │ │ │ ├── sql.go │ │ │ ├── sql_exec.go │ │ │ ├── sql_test.go │ │ │ └── sql_type.go │ │ └── redis/ │ │ ├── command.get.values.go │ │ ├── command.hset.go │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── redis.go │ │ ├── redis.options.go │ │ ├── redis.pb.go │ │ ├── redis.proto │ │ ├── redis.yaml │ │ ├── redis_benchmark_test.go │ │ ├── redis_hset_test.go │ │ ├── redis_key_delete_test.go │ │ ├── redis_key_test.go │ │ ├── redis_list_test.go │ │ ├── redis_options.go │ │ ├── redis_set_test.go │ │ ├── redis_string_test.go │ │ ├── redis_transaction_test.go │ │ ├── redis_type.go │ │ └── redis_zset_test.go │ ├── discovery/ │ │ ├── consul/ │ │ │ └── discovery.go │ │ ├── etcd/ │ │ │ ├── config.go │ │ │ ├── config.option.go │ │ │ ├── config_option.go │ │ │ ├── etcd.go │ │ │ ├── etcd.option.go │ │ │ ├── etcd.pb.go │ │ │ ├── etcd.proto │ │ │ ├── etcd.watch.go │ │ │ ├── etcd.yaml │ │ │ ├── etcd_options.go │ │ │ ├── etcd_test.go │ │ │ └── etcd_type.go │ │ ├── go.mod │ │ └── go.sum │ ├── file-cleanup/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── disk/ │ │ │ ├── disk_cleaner.go │ │ │ ├── disk_cleaner.option.go │ │ │ ├── disk_cleaner.pb.go │ │ │ ├── disk_cleaner.proto │ │ │ └── disk_cleaner_option.go │ │ ├── disk_cleaner_test.go │ │ ├── diskcleaner.yaml │ │ ├── file_cleaner.go │ │ ├── file_cleaner.option.go │ │ ├── file_cleaner_option.go │ │ ├── file_cleaner_test.go │ │ ├── go.mod │ │ └── go.sum │ ├── file-rotate/ │ │ ├── go.mod │ │ ├── go.sum │ │ ├── rotate_file.go │ │ ├── rotate_file.option.go │ │ ├── rotate_file_option.go │ │ └── rotate_file_test.go │ ├── file-transfer/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── file.transfer.go │ │ ├── file.transfer.option.go │ │ ├── file.transfer_option.go │ │ ├── file.transfer_test.go │ │ ├── ft.pb.go │ │ ├── ft.proto │ │ ├── ft.yaml │ │ ├── go.mod │ │ ├── go.sum │ │ └── upload/ │ │ ├── upload.svr.go │ │ └── upload.svr_test.go │ ├── fsnotify/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── fsnotify.go │ │ ├── fsnotify.option.go │ │ ├── fsnotify.pb.go │ │ ├── fsnotify.proto │ │ ├── fsnotify.yaml │ │ ├── fsnotify_option.go │ │ ├── fsnotify_test.go │ │ ├── go.mod │ │ └── go.sum │ ├── gocv/ │ │ ├── cgo/ │ │ │ ├── CMakeLists.txt │ │ │ ├── api/ │ │ │ │ └── openapi-spec/ │ │ │ │ ├── CMakeLists.txt │ │ │ │ ├── Makefile │ │ │ │ ├── gocv/ │ │ │ │ │ ├── CMakeLists.txt │ │ │ │ │ ├── gocv.magick.pb.go │ │ │ │ │ ├── gocv.magick.pb.h │ │ │ │ │ ├── gocv.magick.proto │ │ │ │ │ └── libproto-gocv.a │ │ │ │ ├── proto.gen.go │ │ │ │ ├── scripts/ │ │ │ │ │ └── proto-gen.sh │ │ │ │ ├── thirdparty.cmake │ │ │ │ ├── thirdparty.srv.cmake │ │ │ │ └── types/ │ │ │ │ ├── CMakeLists.txt │ │ │ │ ├── code/ │ │ │ │ │ ├── code.error.go │ │ │ │ │ ├── sdk-go.code.pb.go │ │ │ │ │ ├── sdk-go.code.pb.h │ │ │ │ │ └── sdk-go.code.proto │ │ │ │ ├── libproto-types.a │ │ │ │ ├── sdk-go.types.pb.go │ │ │ │ ├── sdk-go.types.pb.h │ │ │ │ └── sdk-go.types.proto │ │ │ ├── cmake/ │ │ │ │ └── FindProtobuf.cmake │ │ │ ├── gocv/ │ │ │ │ ├── Makefile │ │ │ │ ├── gocv.go │ │ │ │ ├── gocv_test.go │ │ │ │ ├── magick.h │ │ │ │ ├── magick_linux_amd64.cpp │ │ │ │ └── magick_linux_amd64.go │ │ │ ├── pkgconfig/ │ │ │ │ ├── graphics-magick.pc │ │ │ │ ├── opencv2.pc │ │ │ │ ├── opencv4.pc │ │ │ │ ├── protobuf.pc │ │ │ │ ├── pybind11.pc │ │ │ │ └── python3-embed.pc │ │ │ ├── script/ │ │ │ │ └── version.sh │ │ │ ├── swig/ │ │ │ │ ├── gocv/ │ │ │ │ │ ├── Makefile │ │ │ │ │ ├── cgo.go │ │ │ │ │ ├── gocv.go │ │ │ │ │ ├── gocv.h │ │ │ │ │ ├── gocv.swigcxx │ │ │ │ │ ├── gocv_linux_amd64.cpp │ │ │ │ │ ├── gocv_linux_amd64.go │ │ │ │ │ ├── gocv_test.go │ │ │ │ │ ├── gocv_wrap.cxx │ │ │ │ │ └── gocv_wrap.h │ │ │ │ ├── pycv/ │ │ │ │ │ ├── Makefile │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── cgo.go │ │ │ │ │ ├── pycv.go │ │ │ │ │ ├── pycv.h │ │ │ │ │ ├── pycv.py │ │ │ │ │ ├── pycv.swigcxx │ │ │ │ │ ├── pycv_linux_amd64.cpp │ │ │ │ │ ├── pycv_test.go │ │ │ │ │ ├── pycv_wrap.cxx │ │ │ │ │ └── pycv_wrap.h │ │ │ │ └── types/ │ │ │ │ └── pybind11/ │ │ │ │ ├── pybind11.swigcxx │ │ │ │ └── pybind11_mock.h │ │ │ └── third_path/ │ │ │ ├── graphics-magick/ │ │ │ │ ├── bin/ │ │ │ │ │ ├── GraphicsMagick++-config │ │ │ │ │ ├── GraphicsMagick-config │ │ │ │ │ ├── GraphicsMagickWand-config │ │ │ │ │ └── gm │ │ │ │ ├── include/ │ │ │ │ │ ├── GraphicsMagick/ │ │ │ │ │ │ ├── Magick++/ │ │ │ │ │ │ │ ├── Blob.h │ │ │ │ │ │ │ ├── CoderInfo.h │ │ │ │ │ │ │ ├── Color.h │ │ │ │ │ │ │ ├── Drawable.h │ │ │ │ │ │ │ ├── Exception.h │ │ │ │ │ │ │ ├── Geometry.h │ │ │ │ │ │ │ ├── Image.h │ │ │ │ │ │ │ ├── Include.h │ │ │ │ │ │ │ ├── Montage.h │ │ │ │ │ │ │ ├── Pixels.h │ │ │ │ │ │ │ ├── STL.h │ │ │ │ │ │ │ └── TypeMetric.h │ │ │ │ │ │ ├── Magick++.h │ │ │ │ │ │ ├── magick/ │ │ │ │ │ │ │ ├── analyze.h │ │ │ │ │ │ │ ├── api.h │ │ │ │ │ │ │ ├── attribute.h │ │ │ │ │ │ │ ├── average.h │ │ │ │ │ │ │ ├── blob.h │ │ │ │ │ │ │ ├── cdl.h │ │ │ │ │ │ │ ├── channel.h │ │ │ │ │ │ │ ├── color.h │ │ │ │ │ │ │ ├── color_lookup.h │ │ │ │ │ │ │ ├── colormap.h │ │ │ │ │ │ │ ├── colorspace.h │ │ │ │ │ │ │ ├── command.h │ │ │ │ │ │ │ ├── common.h │ │ │ │ │ │ │ ├── compare.h │ │ │ │ │ │ │ ├── composite.h │ │ │ │ │ │ │ ├── compress.h │ │ │ │ │ │ │ ├── confirm_access.h │ │ │ │ │ │ │ ├── constitute.h │ │ │ │ │ │ │ ├── decorate.h │ │ │ │ │ │ │ ├── delegate.h │ │ │ │ │ │ │ ├── deprecate.h │ │ │ │ │ │ │ ├── describe.h │ │ │ │ │ │ │ ├── draw.h │ │ │ │ │ │ │ ├── effect.h │ │ │ │ │ │ │ ├── enhance.h │ │ │ │ │ │ │ ├── error.h │ │ │ │ │ │ │ ├── forward.h │ │ │ │ │ │ │ ├── fx.h │ │ │ │ │ │ │ ├── gem.h │ │ │ │ │ │ │ ├── gradient.h │ │ │ │ │ │ │ ├── hclut.h │ │ │ │ │ │ │ ├── image.h │ │ │ │ │ │ │ ├── list.h │ │ │ │ │ │ │ ├── log.h │ │ │ │ │ │ │ ├── magic.h │ │ │ │ │ │ │ ├── magick.h │ │ │ │ │ │ │ ├── magick_config.h │ │ │ │ │ │ │ ├── magick_types.h │ │ │ │ │ │ │ ├── memory.h │ │ │ │ │ │ │ ├── module.h │ │ │ │ │ │ │ ├── monitor.h │ │ │ │ │ │ │ ├── montage.h │ │ │ │ │ │ │ ├── operator.h │ │ │ │ │ │ │ ├── paint.h │ │ │ │ │ │ │ ├── pixel_cache.h │ │ │ │ │ │ │ ├── pixel_iterator.h │ │ │ │ │ │ │ ├── plasma.h │ │ │ │ │ │ │ ├── profile.h │ │ │ │ │ │ │ ├── quantize.h │ │ │ │ │ │ │ ├── random.h │ │ │ │ │ │ │ ├── registry.h │ │ │ │ │ │ │ ├── render.h │ │ │ │ │ │ │ ├── resize.h │ │ │ │ │ │ │ ├── resource.h │ │ │ │ │ │ │ ├── shear.h │ │ │ │ │ │ │ ├── signature.h │ │ │ │ │ │ │ ├── statistics.h │ │ │ │ │ │ │ ├── symbols.h │ │ │ │ │ │ │ ├── texture.h │ │ │ │ │ │ │ ├── timer.h │ │ │ │ │ │ │ ├── transform.h │ │ │ │ │ │ │ ├── type.h │ │ │ │ │ │ │ ├── utility.h │ │ │ │ │ │ │ └── version.h │ │ │ │ │ │ └── wand/ │ │ │ │ │ │ ├── drawing_wand.h │ │ │ │ │ │ ├── magick_wand.h │ │ │ │ │ │ ├── pixel_wand.h │ │ │ │ │ │ ├── wand_api.h │ │ │ │ │ │ └── wand_symbols.h │ │ │ │ │ ├── Magick++/ │ │ │ │ │ │ ├── Blob.h │ │ │ │ │ │ ├── CoderInfo.h │ │ │ │ │ │ ├── Color.h │ │ │ │ │ │ ├── Drawable.h │ │ │ │ │ │ ├── Exception.h │ │ │ │ │ │ ├── Geometry.h │ │ │ │ │ │ ├── Image.h │ │ │ │ │ │ ├── Include.h │ │ │ │ │ │ ├── Montage.h │ │ │ │ │ │ ├── Pixels.h │ │ │ │ │ │ ├── STL.h │ │ │ │ │ │ └── TypeMetric.h │ │ │ │ │ ├── Magick++.h │ │ │ │ │ ├── magick/ │ │ │ │ │ │ ├── analyze.h │ │ │ │ │ │ ├── api.h │ │ │ │ │ │ ├── attribute.h │ │ │ │ │ │ ├── average.h │ │ │ │ │ │ ├── blob.h │ │ │ │ │ │ ├── cdl.h │ │ │ │ │ │ ├── channel.h │ │ │ │ │ │ ├── color.h │ │ │ │ │ │ ├── color_lookup.h │ │ │ │ │ │ ├── colormap.h │ │ │ │ │ │ ├── colorspace.h │ │ │ │ │ │ ├── command.h │ │ │ │ │ │ ├── common.h │ │ │ │ │ │ ├── compare.h │ │ │ │ │ │ ├── composite.h │ │ │ │ │ │ ├── compress.h │ │ │ │ │ │ ├── confirm_access.h │ │ │ │ │ │ ├── constitute.h │ │ │ │ │ │ ├── decorate.h │ │ │ │ │ │ ├── delegate.h │ │ │ │ │ │ ├── deprecate.h │ │ │ │ │ │ ├── describe.h │ │ │ │ │ │ ├── draw.h │ │ │ │ │ │ ├── effect.h │ │ │ │ │ │ ├── enhance.h │ │ │ │ │ │ ├── error.h │ │ │ │ │ │ ├── forward.h │ │ │ │ │ │ ├── fx.h │ │ │ │ │ │ ├── gem.h │ │ │ │ │ │ ├── gradient.h │ │ │ │ │ │ ├── hclut.h │ │ │ │ │ │ ├── image.h │ │ │ │ │ │ ├── list.h │ │ │ │ │ │ ├── log.h │ │ │ │ │ │ ├── magic.h │ │ │ │ │ │ ├── magick.h │ │ │ │ │ │ ├── magick_config.h │ │ │ │ │ │ ├── magick_types.h │ │ │ │ │ │ ├── memory.h │ │ │ │ │ │ ├── module.h │ │ │ │ │ │ ├── monitor.h │ │ │ │ │ │ ├── montage.h │ │ │ │ │ │ ├── operator.h │ │ │ │ │ │ ├── paint.h │ │ │ │ │ │ ├── pixel_cache.h │ │ │ │ │ │ ├── pixel_iterator.h │ │ │ │ │ │ ├── plasma.h │ │ │ │ │ │ ├── profile.h │ │ │ │ │ │ ├── quantize.h │ │ │ │ │ │ ├── random.h │ │ │ │ │ │ ├── registry.h │ │ │ │ │ │ ├── render.h │ │ │ │ │ │ ├── resize.h │ │ │ │ │ │ ├── resource.h │ │ │ │ │ │ ├── shear.h │ │ │ │ │ │ ├── signature.h │ │ │ │ │ │ ├── statistics.h │ │ │ │ │ │ ├── symbols.h │ │ │ │ │ │ ├── texture.h │ │ │ │ │ │ ├── timer.h │ │ │ │ │ │ ├── transform.h │ │ │ │ │ │ ├── type.h │ │ │ │ │ │ ├── utility.h │ │ │ │ │ │ └── version.h │ │ │ │ │ └── wand/ │ │ │ │ │ ├── drawing_wand.h │ │ │ │ │ ├── magick_wand.h │ │ │ │ │ ├── pixel_wand.h │ │ │ │ │ ├── wand_api.h │ │ │ │ │ └── wand_symbols.h │ │ │ │ ├── lib/ │ │ │ │ │ ├── GraphicsMagick-1.3.35/ │ │ │ │ │ │ └── config/ │ │ │ │ │ │ ├── delegates.mgk │ │ │ │ │ │ ├── type-ghostscript.mgk │ │ │ │ │ │ ├── type-solaris.mgk │ │ │ │ │ │ ├── type-windows.mgk │ │ │ │ │ │ └── type.mgk │ │ │ │ │ ├── libGraphicsMagick++.a │ │ │ │ │ ├── libGraphicsMagick++.so.12.4.3 │ │ │ │ │ ├── libGraphicsMagick.a │ │ │ │ │ ├── libGraphicsMagick.so.3.21.0 │ │ │ │ │ ├── libGraphicsMagickWand.a │ │ │ │ │ ├── libGraphicsMagickWand.so.2.9.4 │ │ │ │ │ ├── libjbig.so.2.0 │ │ │ │ │ ├── libpng15.so.15 │ │ │ │ │ ├── libtiff.so.5 │ │ │ │ │ ├── libtiff.so.5.2.0 │ │ │ │ │ ├── libwebp.so.4 │ │ │ │ │ ├── libwebp.so.4.0.2 │ │ │ │ │ ├── libwebpmux.so.0 │ │ │ │ │ ├── libwebpmux.so.0.0.0 │ │ │ │ │ └── pkgconfig/ │ │ │ │ │ ├── GraphicsMagick++.pc │ │ │ │ │ ├── GraphicsMagick.pc │ │ │ │ │ └── GraphicsMagickWand.pc │ │ │ │ └── share/ │ │ │ │ ├── GraphicsMagick-1.3.35/ │ │ │ │ │ └── config/ │ │ │ │ │ ├── colors.mgk │ │ │ │ │ ├── log.mgk │ │ │ │ │ └── modules.mgk │ │ │ │ ├── doc/ │ │ │ │ │ └── GraphicsMagick/ │ │ │ │ │ ├── ChangeLog │ │ │ │ │ ├── ChangeLog.2001 │ │ │ │ │ ├── ChangeLog.2002 │ │ │ │ │ ├── ChangeLog.2003 │ │ │ │ │ ├── ChangeLog.2004 │ │ │ │ │ ├── ChangeLog.2005 │ │ │ │ │ ├── ChangeLog.2006 │ │ │ │ │ ├── ChangeLog.2007 │ │ │ │ │ ├── ChangeLog.2008 │ │ │ │ │ ├── ChangeLog.2009 │ │ │ │ │ ├── ChangeLog.2010 │ │ │ │ │ ├── ChangeLog.2011 │ │ │ │ │ ├── ChangeLog.2012 │ │ │ │ │ ├── ChangeLog.2013 │ │ │ │ │ ├── ChangeLog.2014 │ │ │ │ │ ├── ChangeLog.2015 │ │ │ │ │ ├── ChangeLog.2016 │ │ │ │ │ ├── ChangeLog.2017 │ │ │ │ │ ├── ChangeLog.2018 │ │ │ │ │ ├── ChangeLog.2019 │ │ │ │ │ ├── Copyright.txt │ │ │ │ │ ├── NEWS.txt │ │ │ │ │ └── www/ │ │ │ │ │ ├── ChangeLog-2001.html │ │ │ │ │ ├── ChangeLog-2002.html │ │ │ │ │ ├── ChangeLog-2003.html │ │ │ │ │ ├── ChangeLog-2004.html │ │ │ │ │ ├── ChangeLog-2005.html │ │ │ │ │ ├── ChangeLog-2006.html │ │ │ │ │ ├── ChangeLog-2007.html │ │ │ │ │ ├── ChangeLog-2008.html │ │ │ │ │ ├── ChangeLog-2009.html │ │ │ │ │ ├── ChangeLog-2010.html │ │ │ │ │ ├── ChangeLog-2011.html │ │ │ │ │ ├── ChangeLog-2012.html │ │ │ │ │ ├── ChangeLog-2013.html │ │ │ │ │ ├── ChangeLog-2014.html │ │ │ │ │ ├── ChangeLog-2015.html │ │ │ │ │ ├── ChangeLog-2016.html │ │ │ │ │ ├── ChangeLog-2017.html │ │ │ │ │ ├── ChangeLog-2018.html │ │ │ │ │ ├── ChangeLog-2019.html │ │ │ │ │ ├── Changelog.html │ │ │ │ │ ├── Changes.html │ │ │ │ │ ├── Copyright.html │ │ │ │ │ ├── FAQ.html │ │ │ │ │ ├── GraphicsMagick.html │ │ │ │ │ ├── Hg.html │ │ │ │ │ ├── INSTALL-unix.html │ │ │ │ │ ├── INSTALL-windows.html │ │ │ │ │ ├── ImageMagickObject.html │ │ │ │ │ ├── Magick++/ │ │ │ │ │ │ ├── Blob.html │ │ │ │ │ │ ├── ChangeLog.html │ │ │ │ │ │ ├── CoderInfo.html │ │ │ │ │ │ ├── Color.html │ │ │ │ │ │ ├── Drawable.html │ │ │ │ │ │ ├── Enumerations.html │ │ │ │ │ │ ├── Exception.html │ │ │ │ │ │ ├── FormatCharacters.html │ │ │ │ │ │ ├── Geometry.html │ │ │ │ │ │ ├── Image.html │ │ │ │ │ │ ├── ImageDesign.html │ │ │ │ │ │ ├── Montage.html │ │ │ │ │ │ ├── PixelPacket.html │ │ │ │ │ │ ├── Pixels.html │ │ │ │ │ │ ├── STL.html │ │ │ │ │ │ ├── TypeMetric.html │ │ │ │ │ │ └── index.html │ │ │ │ │ ├── NEWS.html │ │ │ │ │ ├── OpenMP.html │ │ │ │ │ ├── README.html │ │ │ │ │ ├── animate.html │ │ │ │ │ ├── api/ │ │ │ │ │ │ ├── animate.html │ │ │ │ │ │ ├── annotate.html │ │ │ │ │ │ ├── api.html │ │ │ │ │ │ ├── attribute.html │ │ │ │ │ │ ├── average.html │ │ │ │ │ │ ├── blob.html │ │ │ │ │ │ ├── cdl.html │ │ │ │ │ │ ├── channel.html │ │ │ │ │ │ ├── color.html │ │ │ │ │ │ ├── colormap.html │ │ │ │ │ │ ├── compare.html │ │ │ │ │ │ ├── composite.html │ │ │ │ │ │ ├── confirm_access.html │ │ │ │ │ │ ├── constitute.html │ │ │ │ │ │ ├── decorate.html │ │ │ │ │ │ ├── deprecate.html │ │ │ │ │ │ ├── describe.html │ │ │ │ │ │ ├── display.html │ │ │ │ │ │ ├── draw.html │ │ │ │ │ │ ├── effect.html │ │ │ │ │ │ ├── enhance.html │ │ │ │ │ │ ├── error.html │ │ │ │ │ │ ├── export.html │ │ │ │ │ │ ├── fx.html │ │ │ │ │ │ ├── hclut.html │ │ │ │ │ │ ├── image.html │ │ │ │ │ │ ├── import.html │ │ │ │ │ │ ├── list.html │ │ │ │ │ │ ├── magick.html │ │ │ │ │ │ ├── memory.html │ │ │ │ │ │ ├── monitor.html │ │ │ │ │ │ ├── montage.html │ │ │ │ │ │ ├── operator.html │ │ │ │ │ │ ├── paint.html │ │ │ │ │ │ ├── pixel_cache.html │ │ │ │ │ │ ├── pixel_iterator.html │ │ │ │ │ │ ├── plasma.html │ │ │ │ │ │ ├── profile.html │ │ │ │ │ │ ├── quantize.html │ │ │ │ │ │ ├── registry.html │ │ │ │ │ │ ├── render.html │ │ │ │ │ │ ├── resize.html │ │ │ │ │ │ ├── resource.html │ │ │ │ │ │ ├── segment.html │ │ │ │ │ │ ├── shear.html │ │ │ │ │ │ ├── signature.html │ │ │ │ │ │ ├── statistics.html │ │ │ │ │ │ ├── texture.html │ │ │ │ │ │ ├── transform.html │ │ │ │ │ │ ├── types.html │ │ │ │ │ │ └── widget.html │ │ │ │ │ ├── authors.html │ │ │ │ │ ├── batch.html │ │ │ │ │ ├── benchmark.html │ │ │ │ │ ├── benchmarks.html │ │ │ │ │ ├── bugs.html │ │ │ │ │ ├── color.html │ │ │ │ │ ├── compare.html │ │ │ │ │ ├── composite.html │ │ │ │ │ ├── conjure.html │ │ │ │ │ ├── contribute.html │ │ │ │ │ ├── convert.html │ │ │ │ │ ├── display.html │ │ │ │ │ ├── docutils-api.css │ │ │ │ │ ├── docutils-articles.css │ │ │ │ │ ├── download.html │ │ │ │ │ ├── formats.html │ │ │ │ │ ├── gm.html │ │ │ │ │ ├── identify.html │ │ │ │ │ ├── import.html │ │ │ │ │ ├── index.html │ │ │ │ │ ├── links.html │ │ │ │ │ ├── magick.css │ │ │ │ │ ├── miff.html │ │ │ │ │ ├── mission.html │ │ │ │ │ ├── mogrify.html │ │ │ │ │ ├── montage.html │ │ │ │ │ ├── motion-picture.html │ │ │ │ │ ├── perl.html │ │ │ │ │ ├── process.html │ │ │ │ │ ├── programming.html │ │ │ │ │ ├── project.html │ │ │ │ │ ├── quantize.html │ │ │ │ │ ├── reference.html │ │ │ │ │ ├── security.html │ │ │ │ │ ├── smile.c │ │ │ │ │ ├── thanks.html │ │ │ │ │ ├── time.html │ │ │ │ │ ├── tools.html │ │ │ │ │ ├── utilities.html │ │ │ │ │ ├── version.html │ │ │ │ │ └── wand/ │ │ │ │ │ ├── drawing_wand.html │ │ │ │ │ ├── magick_wand.html │ │ │ │ │ ├── pixel_wand.html │ │ │ │ │ └── wand.html │ │ │ │ └── man/ │ │ │ │ ├── man1/ │ │ │ │ │ ├── GraphicsMagick++-config.1 │ │ │ │ │ ├── GraphicsMagick-config.1 │ │ │ │ │ ├── GraphicsMagickWand-config.1 │ │ │ │ │ └── gm.1 │ │ │ │ ├── man4/ │ │ │ │ │ └── miff.4 │ │ │ │ └── man5/ │ │ │ │ └── quantize.5 │ │ │ ├── opencv2/ │ │ │ │ ├── include/ │ │ │ │ │ ├── opencv/ │ │ │ │ │ │ ├── cv.h │ │ │ │ │ │ ├── cv.hpp │ │ │ │ │ │ ├── cvaux.h │ │ │ │ │ │ ├── cvaux.hpp │ │ │ │ │ │ ├── cvwimage.h │ │ │ │ │ │ ├── cxcore.h │ │ │ │ │ │ ├── cxcore.hpp │ │ │ │ │ │ ├── cxeigen.hpp │ │ │ │ │ │ ├── cxmisc.h │ │ │ │ │ │ ├── highgui.h │ │ │ │ │ │ └── ml.h │ │ │ │ │ └── opencv2/ │ │ │ │ │ ├── calib3d/ │ │ │ │ │ │ └── calib3d.hpp │ │ │ │ │ ├── contrib/ │ │ │ │ │ │ ├── contrib.hpp │ │ │ │ │ │ ├── detection_based_tracker.hpp │ │ │ │ │ │ ├── hybridtracker.hpp │ │ │ │ │ │ ├── openfabmap.hpp │ │ │ │ │ │ └── retina.hpp │ │ │ │ │ ├── features2d/ │ │ │ │ │ │ └── features2d.hpp │ │ │ │ │ ├── flann/ │ │ │ │ │ │ ├── all_indices.h │ │ │ │ │ │ ├── allocator.h │ │ │ │ │ │ ├── any.h │ │ │ │ │ │ ├── autotuned_index.h │ │ │ │ │ │ ├── composite_index.h │ │ │ │ │ │ ├── config.h │ │ │ │ │ │ ├── defines.h │ │ │ │ │ │ ├── dist.h │ │ │ │ │ │ ├── dummy.h │ │ │ │ │ │ ├── dynamic_bitset.h │ │ │ │ │ │ ├── flann.hpp │ │ │ │ │ │ ├── flann_base.hpp │ │ │ │ │ │ ├── general.h │ │ │ │ │ │ ├── ground_truth.h │ │ │ │ │ │ ├── hdf5.h │ │ │ │ │ │ ├── heap.h │ │ │ │ │ │ ├── hierarchical_clustering_index.h │ │ │ │ │ │ ├── index_testing.h │ │ │ │ │ │ ├── kdtree_index.h │ │ │ │ │ │ ├── kdtree_single_index.h │ │ │ │ │ │ ├── kmeans_index.h │ │ │ │ │ │ ├── linear_index.h │ │ │ │ │ │ ├── logger.h │ │ │ │ │ │ ├── lsh_index.h │ │ │ │ │ │ ├── lsh_table.h │ │ │ │ │ │ ├── matrix.h │ │ │ │ │ │ ├── miniflann.hpp │ │ │ │ │ │ ├── nn_index.h │ │ │ │ │ │ ├── object_factory.h │ │ │ │ │ │ ├── params.h │ │ │ │ │ │ ├── random.h │ │ │ │ │ │ ├── result_set.h │ │ │ │ │ │ ├── sampling.h │ │ │ │ │ │ ├── saving.h │ │ │ │ │ │ ├── simplex_downhill.h │ │ │ │ │ │ └── timer.h │ │ │ │ │ ├── gpu/ │ │ │ │ │ │ ├── device/ │ │ │ │ │ │ │ ├── block.hpp │ │ │ │ │ │ │ ├── border_interpolate.hpp │ │ │ │ │ │ │ ├── color.hpp │ │ │ │ │ │ │ ├── common.hpp │ │ │ │ │ │ │ ├── datamov_utils.hpp │ │ │ │ │ │ │ ├── detail/ │ │ │ │ │ │ │ │ ├── color_detail.hpp │ │ │ │ │ │ │ │ ├── reduce.hpp │ │ │ │ │ │ │ │ ├── reduce_key_val.hpp │ │ │ │ │ │ │ │ ├── transform_detail.hpp │ │ │ │ │ │ │ │ ├── type_traits_detail.hpp │ │ │ │ │ │ │ │ └── vec_distance_detail.hpp │ │ │ │ │ │ │ ├── dynamic_smem.hpp │ │ │ │ │ │ │ ├── emulation.hpp │ │ │ │ │ │ │ ├── filters.hpp │ │ │ │ │ │ │ ├── funcattrib.hpp │ │ │ │ │ │ │ ├── functional.hpp │ │ │ │ │ │ │ ├── limits.hpp │ │ │ │ │ │ │ ├── reduce.hpp │ │ │ │ │ │ │ ├── saturate_cast.hpp │ │ │ │ │ │ │ ├── scan.hpp │ │ │ │ │ │ │ ├── simd_functions.hpp │ │ │ │ │ │ │ ├── static_check.hpp │ │ │ │ │ │ │ ├── transform.hpp │ │ │ │ │ │ │ ├── type_traits.hpp │ │ │ │ │ │ │ ├── utility.hpp │ │ │ │ │ │ │ ├── vec_distance.hpp │ │ │ │ │ │ │ ├── vec_math.hpp │ │ │ │ │ │ │ ├── vec_traits.hpp │ │ │ │ │ │ │ ├── warp.hpp │ │ │ │ │ │ │ ├── warp_reduce.hpp │ │ │ │ │ │ │ └── warp_shuffle.hpp │ │ │ │ │ │ ├── devmem2d.hpp │ │ │ │ │ │ ├── gpu.hpp │ │ │ │ │ │ ├── gpumat.hpp │ │ │ │ │ │ └── stream_accessor.hpp │ │ │ │ │ ├── highgui/ │ │ │ │ │ │ ├── cap_ios.h │ │ │ │ │ │ ├── highgui.hpp │ │ │ │ │ │ ├── highgui_c.h │ │ │ │ │ │ └── ios.h │ │ │ │ │ ├── imgproc/ │ │ │ │ │ │ ├── imgproc.hpp │ │ │ │ │ │ ├── imgproc_c.h │ │ │ │ │ │ └── types_c.h │ │ │ │ │ ├── legacy/ │ │ │ │ │ │ ├── blobtrack.hpp │ │ │ │ │ │ ├── compat.hpp │ │ │ │ │ │ ├── legacy.hpp │ │ │ │ │ │ └── streams.hpp │ │ │ │ │ ├── ml/ │ │ │ │ │ │ └── ml.hpp │ │ │ │ │ ├── nonfree/ │ │ │ │ │ │ ├── features2d.hpp │ │ │ │ │ │ ├── gpu.hpp │ │ │ │ │ │ ├── nonfree.hpp │ │ │ │ │ │ └── ocl.hpp │ │ │ │ │ ├── objdetect/ │ │ │ │ │ │ └── objdetect.hpp │ │ │ │ │ ├── ocl/ │ │ │ │ │ │ ├── matrix_operations.hpp │ │ │ │ │ │ └── ocl.hpp │ │ │ │ │ ├── opencv.hpp │ │ │ │ │ ├── opencv_modules.hpp │ │ │ │ │ ├── photo/ │ │ │ │ │ │ ├── photo.hpp │ │ │ │ │ │ └── photo_c.h │ │ │ │ │ ├── stitching/ │ │ │ │ │ │ ├── detail/ │ │ │ │ │ │ │ ├── autocalib.hpp │ │ │ │ │ │ │ ├── blenders.hpp │ │ │ │ │ │ │ ├── camera.hpp │ │ │ │ │ │ │ ├── exposure_compensate.hpp │ │ │ │ │ │ │ ├── matchers.hpp │ │ │ │ │ │ │ ├── motion_estimators.hpp │ │ │ │ │ │ │ ├── seam_finders.hpp │ │ │ │ │ │ │ ├── util.hpp │ │ │ │ │ │ │ ├── util_inl.hpp │ │ │ │ │ │ │ ├── warpers.hpp │ │ │ │ │ │ │ └── warpers_inl.hpp │ │ │ │ │ │ ├── stitcher.hpp │ │ │ │ │ │ └── warpers.hpp │ │ │ │ │ ├── superres/ │ │ │ │ │ │ ├── optical_flow.hpp │ │ │ │ │ │ └── superres.hpp │ │ │ │ │ ├── ts/ │ │ │ │ │ │ ├── gpu_perf.hpp │ │ │ │ │ │ ├── gpu_test.hpp │ │ │ │ │ │ ├── ts.hpp │ │ │ │ │ │ ├── ts_gtest.h │ │ │ │ │ │ └── ts_perf.hpp │ │ │ │ │ ├── video/ │ │ │ │ │ │ ├── background_segm.hpp │ │ │ │ │ │ ├── tracking.hpp │ │ │ │ │ │ └── video.hpp │ │ │ │ │ └── videostab/ │ │ │ │ │ ├── deblurring.hpp │ │ │ │ │ ├── fast_marching.hpp │ │ │ │ │ ├── fast_marching_inl.hpp │ │ │ │ │ ├── frame_source.hpp │ │ │ │ │ ├── global_motion.hpp │ │ │ │ │ ├── inpainting.hpp │ │ │ │ │ ├── log.hpp │ │ │ │ │ ├── motion_stabilizing.hpp │ │ │ │ │ ├── optical_flow.hpp │ │ │ │ │ ├── stabilizer.hpp │ │ │ │ │ └── videostab.hpp │ │ │ │ ├── lib/ │ │ │ │ │ ├── libIlmImf.a │ │ │ │ │ ├── libjpeg.a │ │ │ │ │ ├── libjpeg.so.62.3.0 │ │ │ │ │ ├── liblibjasper.a │ │ │ │ │ ├── liblibpng.a │ │ │ │ │ ├── liblibtiff.a │ │ │ │ │ ├── libopencv_calib3d.so.2.4.12 │ │ │ │ │ ├── libopencv_contrib.so.2.4.12 │ │ │ │ │ ├── libopencv_core.so.2.4.12 │ │ │ │ │ ├── libopencv_features2d.so.2.4.12 │ │ │ │ │ ├── libopencv_flann.so.2.4.12 │ │ │ │ │ ├── libopencv_gpu.so.2.4.12 │ │ │ │ │ ├── libopencv_highgui.so.2.4.12 │ │ │ │ │ ├── libopencv_imgproc.so.2.4.12 │ │ │ │ │ ├── libopencv_legacy.so.2.4.12 │ │ │ │ │ ├── libopencv_ml.so.2.4.12 │ │ │ │ │ ├── libopencv_nonfree.so.2.4.12 │ │ │ │ │ ├── libopencv_objdetect.so.2.4.12 │ │ │ │ │ ├── libopencv_ocl.so.2.4.12 │ │ │ │ │ ├── libopencv_photo.so.2.4.12 │ │ │ │ │ ├── libopencv_stitching.so.2.4.12 │ │ │ │ │ ├── libopencv_superres.so.2.4.12 │ │ │ │ │ ├── libopencv_ts.a │ │ │ │ │ ├── libopencv_video.so.2.4.12 │ │ │ │ │ ├── libopencv_videostab.so.2.4.12 │ │ │ │ │ ├── libturbojpeg.a │ │ │ │ │ ├── libturbojpeg.so.0.2.0 │ │ │ │ │ └── pkgconfig/ │ │ │ │ │ └── opencv.pc │ │ │ │ └── version.txt │ │ │ ├── opencv4/ │ │ │ │ ├── .gitignore │ │ │ │ ├── README.md │ │ │ │ ├── include/ │ │ │ │ │ └── opencv2/ │ │ │ │ │ ├── calib3d/ │ │ │ │ │ │ ├── calib3d.hpp │ │ │ │ │ │ └── calib3d_c.h │ │ │ │ │ ├── calib3d.hpp │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── affine.hpp │ │ │ │ │ │ ├── async.hpp │ │ │ │ │ │ ├── base.hpp │ │ │ │ │ │ ├── bindings_utils.hpp │ │ │ │ │ │ ├── bufferpool.hpp │ │ │ │ │ │ ├── check.hpp │ │ │ │ │ │ ├── core.hpp │ │ │ │ │ │ ├── core_c.h │ │ │ │ │ │ ├── cuda/ │ │ │ │ │ │ │ ├── block.hpp │ │ │ │ │ │ │ ├── border_interpolate.hpp │ │ │ │ │ │ │ ├── color.hpp │ │ │ │ │ │ │ ├── common.hpp │ │ │ │ │ │ │ ├── datamov_utils.hpp │ │ │ │ │ │ │ ├── detail/ │ │ │ │ │ │ │ │ ├── color_detail.hpp │ │ │ │ │ │ │ │ ├── reduce.hpp │ │ │ │ │ │ │ │ ├── reduce_key_val.hpp │ │ │ │ │ │ │ │ ├── transform_detail.hpp │ │ │ │ │ │ │ │ ├── type_traits_detail.hpp │ │ │ │ │ │ │ │ └── vec_distance_detail.hpp │ │ │ │ │ │ │ ├── dynamic_smem.hpp │ │ │ │ │ │ │ ├── emulation.hpp │ │ │ │ │ │ │ ├── filters.hpp │ │ │ │ │ │ │ ├── funcattrib.hpp │ │ │ │ │ │ │ ├── functional.hpp │ │ │ │ │ │ │ ├── limits.hpp │ │ │ │ │ │ │ ├── reduce.hpp │ │ │ │ │ │ │ ├── saturate_cast.hpp │ │ │ │ │ │ │ ├── scan.hpp │ │ │ │ │ │ │ ├── simd_functions.hpp │ │ │ │ │ │ │ ├── transform.hpp │ │ │ │ │ │ │ ├── type_traits.hpp │ │ │ │ │ │ │ ├── utility.hpp │ │ │ │ │ │ │ ├── vec_distance.hpp │ │ │ │ │ │ │ ├── vec_math.hpp │ │ │ │ │ │ │ ├── vec_traits.hpp │ │ │ │ │ │ │ ├── warp.hpp │ │ │ │ │ │ │ ├── warp_reduce.hpp │ │ │ │ │ │ │ └── warp_shuffle.hpp │ │ │ │ │ │ ├── cuda.hpp │ │ │ │ │ │ ├── cuda.inl.hpp │ │ │ │ │ │ ├── cuda_stream_accessor.hpp │ │ │ │ │ │ ├── cuda_types.hpp │ │ │ │ │ │ ├── cv_cpu_dispatch.h │ │ │ │ │ │ ├── cv_cpu_helper.h │ │ │ │ │ │ ├── cvdef.h │ │ │ │ │ │ ├── cvstd.hpp │ │ │ │ │ │ ├── cvstd.inl.hpp │ │ │ │ │ │ ├── cvstd_wrapper.hpp │ │ │ │ │ │ ├── detail/ │ │ │ │ │ │ │ ├── async_promise.hpp │ │ │ │ │ │ │ └── exception_ptr.hpp │ │ │ │ │ │ ├── directx.hpp │ │ │ │ │ │ ├── dualquaternion.hpp │ │ │ │ │ │ ├── dualquaternion.inl.hpp │ │ │ │ │ │ ├── eigen.hpp │ │ │ │ │ │ ├── fast_math.hpp │ │ │ │ │ │ ├── hal/ │ │ │ │ │ │ │ ├── hal.hpp │ │ │ │ │ │ │ ├── interface.h │ │ │ │ │ │ │ ├── intrin.hpp │ │ │ │ │ │ │ ├── intrin_avx.hpp │ │ │ │ │ │ │ ├── intrin_avx512.hpp │ │ │ │ │ │ │ ├── intrin_cpp.hpp │ │ │ │ │ │ │ ├── intrin_forward.hpp │ │ │ │ │ │ │ ├── intrin_msa.hpp │ │ │ │ │ │ │ ├── intrin_neon.hpp │ │ │ │ │ │ │ ├── intrin_rvv.hpp │ │ │ │ │ │ │ ├── intrin_rvv071.hpp │ │ │ │ │ │ │ ├── intrin_sse.hpp │ │ │ │ │ │ │ ├── intrin_sse_em.hpp │ │ │ │ │ │ │ ├── intrin_vsx.hpp │ │ │ │ │ │ │ ├── intrin_wasm.hpp │ │ │ │ │ │ │ ├── msa_macros.h │ │ │ │ │ │ │ └── simd_utils.impl.hpp │ │ │ │ │ │ ├── mat.hpp │ │ │ │ │ │ ├── mat.inl.hpp │ │ │ │ │ │ ├── matx.hpp │ │ │ │ │ │ ├── neon_utils.hpp │ │ │ │ │ │ ├── ocl.hpp │ │ │ │ │ │ ├── ocl_genbase.hpp │ │ │ │ │ │ ├── opencl/ │ │ │ │ │ │ │ ├── ocl_defs.hpp │ │ │ │ │ │ │ ├── opencl_info.hpp │ │ │ │ │ │ │ ├── opencl_svm.hpp │ │ │ │ │ │ │ └── runtime/ │ │ │ │ │ │ │ ├── autogenerated/ │ │ │ │ │ │ │ │ ├── opencl_clblas.hpp │ │ │ │ │ │ │ │ ├── opencl_clfft.hpp │ │ │ │ │ │ │ │ ├── opencl_core.hpp │ │ │ │ │ │ │ │ ├── opencl_core_wrappers.hpp │ │ │ │ │ │ │ │ ├── opencl_gl.hpp │ │ │ │ │ │ │ │ └── opencl_gl_wrappers.hpp │ │ │ │ │ │ │ ├── opencl_clblas.hpp │ │ │ │ │ │ │ ├── opencl_clfft.hpp │ │ │ │ │ │ │ ├── opencl_core.hpp │ │ │ │ │ │ │ ├── opencl_core_wrappers.hpp │ │ │ │ │ │ │ ├── opencl_gl.hpp │ │ │ │ │ │ │ ├── opencl_gl_wrappers.hpp │ │ │ │ │ │ │ ├── opencl_svm_20.hpp │ │ │ │ │ │ │ ├── opencl_svm_definitions.hpp │ │ │ │ │ │ │ └── opencl_svm_hsa_extension.hpp │ │ │ │ │ │ ├── opengl.hpp │ │ │ │ │ │ ├── operations.hpp │ │ │ │ │ │ ├── optim.hpp │ │ │ │ │ │ ├── ovx.hpp │ │ │ │ │ │ ├── parallel/ │ │ │ │ │ │ │ ├── backend/ │ │ │ │ │ │ │ │ ├── parallel_for.openmp.hpp │ │ │ │ │ │ │ │ └── parallel_for.tbb.hpp │ │ │ │ │ │ │ └── parallel_backend.hpp │ │ │ │ │ │ ├── persistence.hpp │ │ │ │ │ │ ├── quaternion.hpp │ │ │ │ │ │ ├── quaternion.inl.hpp │ │ │ │ │ │ ├── saturate.hpp │ │ │ │ │ │ ├── simd_intrinsics.hpp │ │ │ │ │ │ ├── softfloat.hpp │ │ │ │ │ │ ├── sse_utils.hpp │ │ │ │ │ │ ├── traits.hpp │ │ │ │ │ │ ├── types.hpp │ │ │ │ │ │ ├── types_c.h │ │ │ │ │ │ ├── utility.hpp │ │ │ │ │ │ ├── utils/ │ │ │ │ │ │ │ ├── allocator_stats.hpp │ │ │ │ │ │ │ ├── allocator_stats.impl.hpp │ │ │ │ │ │ │ ├── filesystem.hpp │ │ │ │ │ │ │ ├── instrumentation.hpp │ │ │ │ │ │ │ ├── logger.defines.hpp │ │ │ │ │ │ │ ├── logger.hpp │ │ │ │ │ │ │ ├── logtag.hpp │ │ │ │ │ │ │ ├── tls.hpp │ │ │ │ │ │ │ └── trace.hpp │ │ │ │ │ │ ├── va_intel.hpp │ │ │ │ │ │ ├── version.hpp │ │ │ │ │ │ └── vsx_utils.hpp │ │ │ │ │ ├── core.hpp │ │ │ │ │ ├── cvconfig.h │ │ │ │ │ ├── dnn/ │ │ │ │ │ │ ├── all_layers.hpp │ │ │ │ │ │ ├── dict.hpp │ │ │ │ │ │ ├── dnn.hpp │ │ │ │ │ │ ├── dnn.inl.hpp │ │ │ │ │ │ ├── layer.details.hpp │ │ │ │ │ │ ├── layer.hpp │ │ │ │ │ │ ├── shape_utils.hpp │ │ │ │ │ │ ├── utils/ │ │ │ │ │ │ │ └── inference_engine.hpp │ │ │ │ │ │ └── version.hpp │ │ │ │ │ ├── dnn.hpp │ │ │ │ │ ├── features2d/ │ │ │ │ │ │ ├── features2d.hpp │ │ │ │ │ │ └── hal/ │ │ │ │ │ │ └── interface.h │ │ │ │ │ ├── features2d.hpp │ │ │ │ │ ├── flann/ │ │ │ │ │ │ ├── all_indices.h │ │ │ │ │ │ ├── allocator.h │ │ │ │ │ │ ├── any.h │ │ │ │ │ │ ├── autotuned_index.h │ │ │ │ │ │ ├── composite_index.h │ │ │ │ │ │ ├── config.h │ │ │ │ │ │ ├── defines.h │ │ │ │ │ │ ├── dist.h │ │ │ │ │ │ ├── dummy.h │ │ │ │ │ │ ├── dynamic_bitset.h │ │ │ │ │ │ ├── flann.hpp │ │ │ │ │ │ ├── flann_base.hpp │ │ │ │ │ │ ├── general.h │ │ │ │ │ │ ├── ground_truth.h │ │ │ │ │ │ ├── hdf5.h │ │ │ │ │ │ ├── heap.h │ │ │ │ │ │ ├── hierarchical_clustering_index.h │ │ │ │ │ │ ├── index_testing.h │ │ │ │ │ │ ├── kdtree_index.h │ │ │ │ │ │ ├── kdtree_single_index.h │ │ │ │ │ │ ├── kmeans_index.h │ │ │ │ │ │ ├── linear_index.h │ │ │ │ │ │ ├── logger.h │ │ │ │ │ │ ├── lsh_index.h │ │ │ │ │ │ ├── lsh_table.h │ │ │ │ │ │ ├── matrix.h │ │ │ │ │ │ ├── miniflann.hpp │ │ │ │ │ │ ├── nn_index.h │ │ │ │ │ │ ├── object_factory.h │ │ │ │ │ │ ├── params.h │ │ │ │ │ │ ├── random.h │ │ │ │ │ │ ├── result_set.h │ │ │ │ │ │ ├── sampling.h │ │ │ │ │ │ ├── saving.h │ │ │ │ │ │ ├── simplex_downhill.h │ │ │ │ │ │ └── timer.h │ │ │ │ │ ├── flann.hpp │ │ │ │ │ ├── gapi/ │ │ │ │ │ │ ├── core.hpp │ │ │ │ │ │ ├── cpu/ │ │ │ │ │ │ │ ├── core.hpp │ │ │ │ │ │ │ ├── gcpukernel.hpp │ │ │ │ │ │ │ ├── imgproc.hpp │ │ │ │ │ │ │ ├── stereo.hpp │ │ │ │ │ │ │ └── video.hpp │ │ │ │ │ │ ├── fluid/ │ │ │ │ │ │ │ ├── core.hpp │ │ │ │ │ │ │ ├── gfluidbuffer.hpp │ │ │ │ │ │ │ ├── gfluidkernel.hpp │ │ │ │ │ │ │ └── imgproc.hpp │ │ │ │ │ │ ├── garg.hpp │ │ │ │ │ │ ├── garray.hpp │ │ │ │ │ │ ├── gasync_context.hpp │ │ │ │ │ │ ├── gcall.hpp │ │ │ │ │ │ ├── gcommon.hpp │ │ │ │ │ │ ├── gcompiled.hpp │ │ │ │ │ │ ├── gcompiled_async.hpp │ │ │ │ │ │ ├── gcompoundkernel.hpp │ │ │ │ │ │ ├── gcomputation.hpp │ │ │ │ │ │ ├── gcomputation_async.hpp │ │ │ │ │ │ ├── gframe.hpp │ │ │ │ │ │ ├── gkernel.hpp │ │ │ │ │ │ ├── gmat.hpp │ │ │ │ │ │ ├── gmetaarg.hpp │ │ │ │ │ │ ├── gopaque.hpp │ │ │ │ │ │ ├── gproto.hpp │ │ │ │ │ │ ├── gpu/ │ │ │ │ │ │ │ ├── core.hpp │ │ │ │ │ │ │ ├── ggpukernel.hpp │ │ │ │ │ │ │ └── imgproc.hpp │ │ │ │ │ │ ├── gscalar.hpp │ │ │ │ │ │ ├── gstreaming.hpp │ │ │ │ │ │ ├── gtransform.hpp │ │ │ │ │ │ ├── gtype_traits.hpp │ │ │ │ │ │ ├── gtyped.hpp │ │ │ │ │ │ ├── imgproc.hpp │ │ │ │ │ │ ├── infer/ │ │ │ │ │ │ │ ├── bindings_ie.hpp │ │ │ │ │ │ │ ├── ie.hpp │ │ │ │ │ │ │ ├── onnx.hpp │ │ │ │ │ │ │ └── parsers.hpp │ │ │ │ │ │ ├── infer.hpp │ │ │ │ │ │ ├── media.hpp │ │ │ │ │ │ ├── ocl/ │ │ │ │ │ │ │ ├── core.hpp │ │ │ │ │ │ │ ├── goclkernel.hpp │ │ │ │ │ │ │ └── imgproc.hpp │ │ │ │ │ │ ├── opencv_includes.hpp │ │ │ │ │ │ ├── operators.hpp │ │ │ │ │ │ ├── own/ │ │ │ │ │ │ │ ├── assert.hpp │ │ │ │ │ │ │ ├── convert.hpp │ │ │ │ │ │ │ ├── cvdefs.hpp │ │ │ │ │ │ │ ├── exports.hpp │ │ │ │ │ │ │ ├── mat.hpp │ │ │ │ │ │ │ ├── saturate.hpp │ │ │ │ │ │ │ ├── scalar.hpp │ │ │ │ │ │ │ └── types.hpp │ │ │ │ │ │ ├── plaidml/ │ │ │ │ │ │ │ ├── core.hpp │ │ │ │ │ │ │ ├── gplaidmlkernel.hpp │ │ │ │ │ │ │ └── plaidml.hpp │ │ │ │ │ │ ├── python/ │ │ │ │ │ │ │ └── python.hpp │ │ │ │ │ │ ├── render/ │ │ │ │ │ │ │ ├── render.hpp │ │ │ │ │ │ │ └── render_types.hpp │ │ │ │ │ │ ├── render.hpp │ │ │ │ │ │ ├── rmat.hpp │ │ │ │ │ │ ├── s11n/ │ │ │ │ │ │ │ └── base.hpp │ │ │ │ │ │ ├── s11n.hpp │ │ │ │ │ │ ├── stereo.hpp │ │ │ │ │ │ ├── streaming/ │ │ │ │ │ │ │ ├── cap.hpp │ │ │ │ │ │ │ ├── desync.hpp │ │ │ │ │ │ │ ├── format.hpp │ │ │ │ │ │ │ ├── meta.hpp │ │ │ │ │ │ │ ├── source.hpp │ │ │ │ │ │ │ └── sync.hpp │ │ │ │ │ │ ├── util/ │ │ │ │ │ │ │ ├── any.hpp │ │ │ │ │ │ │ ├── compiler_hints.hpp │ │ │ │ │ │ │ ├── copy_through_move.hpp │ │ │ │ │ │ │ ├── optional.hpp │ │ │ │ │ │ │ ├── throw.hpp │ │ │ │ │ │ │ ├── type_traits.hpp │ │ │ │ │ │ │ ├── util.hpp │ │ │ │ │ │ │ └── variant.hpp │ │ │ │ │ │ └── video.hpp │ │ │ │ │ ├── gapi.hpp │ │ │ │ │ ├── highgui/ │ │ │ │ │ │ ├── highgui.hpp │ │ │ │ │ │ └── highgui_c.h │ │ │ │ │ ├── highgui.hpp │ │ │ │ │ ├── imgcodecs/ │ │ │ │ │ │ ├── imgcodecs.hpp │ │ │ │ │ │ ├── imgcodecs_c.h │ │ │ │ │ │ ├── ios.h │ │ │ │ │ │ ├── legacy/ │ │ │ │ │ │ │ └── constants_c.h │ │ │ │ │ │ └── macosx.h │ │ │ │ │ ├── imgcodecs.hpp │ │ │ │ │ ├── imgproc/ │ │ │ │ │ │ ├── bindings.hpp │ │ │ │ │ │ ├── detail/ │ │ │ │ │ │ │ └── gcgraph.hpp │ │ │ │ │ │ ├── hal/ │ │ │ │ │ │ │ ├── hal.hpp │ │ │ │ │ │ │ └── interface.h │ │ │ │ │ │ ├── imgproc.hpp │ │ │ │ │ │ ├── imgproc_c.h │ │ │ │ │ │ ├── segmentation.hpp │ │ │ │ │ │ └── types_c.h │ │ │ │ │ ├── imgproc.hpp │ │ │ │ │ ├── ml/ │ │ │ │ │ │ ├── ml.hpp │ │ │ │ │ │ └── ml.inl.hpp │ │ │ │ │ ├── ml.hpp │ │ │ │ │ ├── objdetect/ │ │ │ │ │ │ ├── detection_based_tracker.hpp │ │ │ │ │ │ └── objdetect.hpp │ │ │ │ │ ├── objdetect.hpp │ │ │ │ │ ├── opencv.hpp │ │ │ │ │ ├── opencv_modules.hpp │ │ │ │ │ ├── photo/ │ │ │ │ │ │ ├── cuda.hpp │ │ │ │ │ │ ├── legacy/ │ │ │ │ │ │ │ └── constants_c.h │ │ │ │ │ │ └── photo.hpp │ │ │ │ │ ├── photo.hpp │ │ │ │ │ ├── stitching/ │ │ │ │ │ │ ├── detail/ │ │ │ │ │ │ │ ├── autocalib.hpp │ │ │ │ │ │ │ ├── blenders.hpp │ │ │ │ │ │ │ ├── camera.hpp │ │ │ │ │ │ │ ├── exposure_compensate.hpp │ │ │ │ │ │ │ ├── matchers.hpp │ │ │ │ │ │ │ ├── motion_estimators.hpp │ │ │ │ │ │ │ ├── seam_finders.hpp │ │ │ │ │ │ │ ├── timelapsers.hpp │ │ │ │ │ │ │ ├── util.hpp │ │ │ │ │ │ │ ├── util_inl.hpp │ │ │ │ │ │ │ ├── warpers.hpp │ │ │ │ │ │ │ └── warpers_inl.hpp │ │ │ │ │ │ └── warpers.hpp │ │ │ │ │ ├── stitching.hpp │ │ │ │ │ ├── video/ │ │ │ │ │ │ ├── background_segm.hpp │ │ │ │ │ │ ├── detail/ │ │ │ │ │ │ │ └── tracking.detail.hpp │ │ │ │ │ │ ├── legacy/ │ │ │ │ │ │ │ └── constants_c.h │ │ │ │ │ │ ├── tracking.hpp │ │ │ │ │ │ └── video.hpp │ │ │ │ │ ├── video.hpp │ │ │ │ │ ├── videoio/ │ │ │ │ │ │ ├── cap_ios.h │ │ │ │ │ │ ├── legacy/ │ │ │ │ │ │ │ └── constants_c.h │ │ │ │ │ │ ├── registry.hpp │ │ │ │ │ │ ├── videoio.hpp │ │ │ │ │ │ └── videoio_c.h │ │ │ │ │ └── videoio.hpp │ │ │ │ └── lib64/ │ │ │ │ ├── cmake/ │ │ │ │ │ └── opencv4/ │ │ │ │ │ ├── OpenCVConfig-version.cmake │ │ │ │ │ ├── OpenCVConfig.cmake │ │ │ │ │ ├── OpenCVModules-release.cmake │ │ │ │ │ └── OpenCVModules.cmake │ │ │ │ ├── libopencv_calib3d.so.4.5.3 │ │ │ │ ├── libopencv_core.so.4.5.3 │ │ │ │ ├── libopencv_dnn.so.4.5.3 │ │ │ │ ├── libopencv_features2d.so.4.5.3 │ │ │ │ ├── libopencv_flann.so.4.5.3 │ │ │ │ ├── libopencv_gapi.so.4.5.3 │ │ │ │ ├── libopencv_highgui.so.4.5.3 │ │ │ │ ├── libopencv_imgcodecs.so.4.5.3 │ │ │ │ ├── libopencv_imgproc.so.4.5.3 │ │ │ │ ├── libopencv_ml.so.4.5.3 │ │ │ │ ├── libopencv_objdetect.so.4.5.3 │ │ │ │ ├── libopencv_photo.so.4.5.3 │ │ │ │ ├── libopencv_stitching.so.4.5.3 │ │ │ │ ├── libopencv_video.so.4.5.3 │ │ │ │ ├── libopencv_videoio.so.4.5.3 │ │ │ │ └── pkgconfig/ │ │ │ │ └── opencv4.pc │ │ │ ├── protobuf/ │ │ │ │ ├── bin/ │ │ │ │ │ └── protoc │ │ │ │ ├── include/ │ │ │ │ │ └── google/ │ │ │ │ │ └── protobuf/ │ │ │ │ │ ├── any.h │ │ │ │ │ ├── any.pb.h │ │ │ │ │ ├── any.proto │ │ │ │ │ ├── api.pb.h │ │ │ │ │ ├── api.proto │ │ │ │ │ ├── arena.h │ │ │ │ │ ├── arena_impl.h │ │ │ │ │ ├── arenastring.h │ │ │ │ │ ├── compiler/ │ │ │ │ │ │ ├── code_generator.h │ │ │ │ │ │ ├── command_line_interface.h │ │ │ │ │ │ ├── cpp/ │ │ │ │ │ │ │ └── cpp_generator.h │ │ │ │ │ │ ├── csharp/ │ │ │ │ │ │ │ ├── csharp_generator.h │ │ │ │ │ │ │ └── csharp_names.h │ │ │ │ │ │ ├── importer.h │ │ │ │ │ │ ├── java/ │ │ │ │ │ │ │ ├── java_generator.h │ │ │ │ │ │ │ └── java_names.h │ │ │ │ │ │ ├── js/ │ │ │ │ │ │ │ ├── js_generator.h │ │ │ │ │ │ │ └── well_known_types_embed.h │ │ │ │ │ │ ├── objectivec/ │ │ │ │ │ │ │ ├── objectivec_generator.h │ │ │ │ │ │ │ └── objectivec_helpers.h │ │ │ │ │ │ ├── parser.h │ │ │ │ │ │ ├── php/ │ │ │ │ │ │ │ └── php_generator.h │ │ │ │ │ │ ├── plugin.h │ │ │ │ │ │ ├── plugin.pb.h │ │ │ │ │ │ ├── plugin.proto │ │ │ │ │ │ ├── python/ │ │ │ │ │ │ │ └── python_generator.h │ │ │ │ │ │ └── ruby/ │ │ │ │ │ │ └── ruby_generator.h │ │ │ │ │ ├── descriptor.h │ │ │ │ │ ├── descriptor.pb.h │ │ │ │ │ ├── descriptor.proto │ │ │ │ │ ├── descriptor_database.h │ │ │ │ │ ├── duration.pb.h │ │ │ │ │ ├── duration.proto │ │ │ │ │ ├── dynamic_message.h │ │ │ │ │ ├── empty.pb.h │ │ │ │ │ ├── empty.proto │ │ │ │ │ ├── extension_set.h │ │ │ │ │ ├── field_mask.pb.h │ │ │ │ │ ├── field_mask.proto │ │ │ │ │ ├── generated_enum_reflection.h │ │ │ │ │ ├── generated_enum_util.h │ │ │ │ │ ├── generated_message_reflection.h │ │ │ │ │ ├── generated_message_table_driven.h │ │ │ │ │ ├── generated_message_util.h │ │ │ │ │ ├── has_bits.h │ │ │ │ │ ├── implicit_weak_message.h │ │ │ │ │ ├── inlined_string_field.h │ │ │ │ │ ├── io/ │ │ │ │ │ │ ├── coded_stream.h │ │ │ │ │ │ ├── gzip_stream.h │ │ │ │ │ │ ├── printer.h │ │ │ │ │ │ ├── strtod.h │ │ │ │ │ │ ├── tokenizer.h │ │ │ │ │ │ ├── zero_copy_stream.h │ │ │ │ │ │ ├── zero_copy_stream_impl.h │ │ │ │ │ │ └── zero_copy_stream_impl_lite.h │ │ │ │ │ ├── map.h │ │ │ │ │ ├── map_entry.h │ │ │ │ │ ├── map_entry_lite.h │ │ │ │ │ ├── map_field.h │ │ │ │ │ ├── map_field_inl.h │ │ │ │ │ ├── map_field_lite.h │ │ │ │ │ ├── map_type_handler.h │ │ │ │ │ ├── message.h │ │ │ │ │ ├── message_lite.h │ │ │ │ │ ├── metadata.h │ │ │ │ │ ├── metadata_lite.h │ │ │ │ │ ├── reflection.h │ │ │ │ │ ├── reflection_ops.h │ │ │ │ │ ├── repeated_field.h │ │ │ │ │ ├── service.h │ │ │ │ │ ├── source_context.pb.h │ │ │ │ │ ├── source_context.proto │ │ │ │ │ ├── struct.pb.h │ │ │ │ │ ├── struct.proto │ │ │ │ │ ├── stubs/ │ │ │ │ │ │ ├── bytestream.h │ │ │ │ │ │ ├── callback.h │ │ │ │ │ │ ├── casts.h │ │ │ │ │ │ ├── common.h │ │ │ │ │ │ ├── fastmem.h │ │ │ │ │ │ ├── hash.h │ │ │ │ │ │ ├── logging.h │ │ │ │ │ │ ├── macros.h │ │ │ │ │ │ ├── mutex.h │ │ │ │ │ │ ├── once.h │ │ │ │ │ │ ├── platform_macros.h │ │ │ │ │ │ ├── port.h │ │ │ │ │ │ ├── singleton.h │ │ │ │ │ │ ├── status.h │ │ │ │ │ │ ├── stl_util.h │ │ │ │ │ │ ├── stringpiece.h │ │ │ │ │ │ └── template_util.h │ │ │ │ │ ├── text_format.h │ │ │ │ │ ├── timestamp.pb.h │ │ │ │ │ ├── timestamp.proto │ │ │ │ │ ├── type.pb.h │ │ │ │ │ ├── type.proto │ │ │ │ │ ├── unknown_field_set.h │ │ │ │ │ ├── util/ │ │ │ │ │ │ ├── delimited_message_util.h │ │ │ │ │ │ ├── field_comparator.h │ │ │ │ │ │ ├── field_mask_util.h │ │ │ │ │ │ ├── json_util.h │ │ │ │ │ │ ├── message_differencer.h │ │ │ │ │ │ ├── time_util.h │ │ │ │ │ │ ├── type_resolver.h │ │ │ │ │ │ └── type_resolver_util.h │ │ │ │ │ ├── wire_format.h │ │ │ │ │ ├── wire_format_lite.h │ │ │ │ │ ├── wire_format_lite_inl.h │ │ │ │ │ ├── wrappers.pb.h │ │ │ │ │ └── wrappers.proto │ │ │ │ └── lib/ │ │ │ │ ├── libprotobuf-lite.a │ │ │ │ ├── libprotobuf.a │ │ │ │ ├── libprotoc.a │ │ │ │ └── pkgconfig/ │ │ │ │ ├── protobuf-lite.pc │ │ │ │ └── protobuf.pc │ │ │ └── pybind11/ │ │ │ ├── CMakeLists.txt │ │ │ ├── LICENSE │ │ │ ├── MANIFEST.in │ │ │ ├── README.rst │ │ │ ├── docs/ │ │ │ │ ├── Doxyfile │ │ │ │ ├── Makefile │ │ │ │ ├── _static/ │ │ │ │ │ └── css/ │ │ │ │ │ └── custom.css │ │ │ │ ├── advanced/ │ │ │ │ │ ├── cast/ │ │ │ │ │ │ ├── chrono.rst │ │ │ │ │ │ ├── custom.rst │ │ │ │ │ │ ├── eigen.rst │ │ │ │ │ │ ├── functional.rst │ │ │ │ │ │ ├── index.rst │ │ │ │ │ │ ├── overview.rst │ │ │ │ │ │ ├── stl.rst │ │ │ │ │ │ └── strings.rst │ │ │ │ │ ├── classes.rst │ │ │ │ │ ├── embedding.rst │ │ │ │ │ ├── exceptions.rst │ │ │ │ │ ├── functions.rst │ │ │ │ │ ├── misc.rst │ │ │ │ │ ├── pycpp/ │ │ │ │ │ │ ├── index.rst │ │ │ │ │ │ ├── numpy.rst │ │ │ │ │ │ ├── object.rst │ │ │ │ │ │ └── utilities.rst │ │ │ │ │ └── smart_ptrs.rst │ │ │ │ ├── basics.rst │ │ │ │ ├── benchmark.py │ │ │ │ ├── benchmark.rst │ │ │ │ ├── changelog.rst │ │ │ │ ├── classes.rst │ │ │ │ ├── cmake/ │ │ │ │ │ └── index.rst │ │ │ │ ├── compiling.rst │ │ │ │ ├── conf.py │ │ │ │ ├── faq.rst │ │ │ │ ├── index.rst │ │ │ │ ├── installing.rst │ │ │ │ ├── limitations.rst │ │ │ │ ├── reference.rst │ │ │ │ ├── release.rst │ │ │ │ ├── requirements.txt │ │ │ │ └── upgrade.rst │ │ │ ├── include/ │ │ │ │ └── pybind11/ │ │ │ │ ├── attr.h │ │ │ │ ├── buffer_info.h │ │ │ │ ├── cast.h │ │ │ │ ├── chrono.h │ │ │ │ ├── common.h │ │ │ │ ├── complex.h │ │ │ │ ├── detail/ │ │ │ │ │ ├── class.h │ │ │ │ │ ├── common.h │ │ │ │ │ ├── descr.h │ │ │ │ │ ├── init.h │ │ │ │ │ ├── internals.h │ │ │ │ │ ├── type_caster_base.h │ │ │ │ │ └── typeid.h │ │ │ │ ├── eigen/ │ │ │ │ │ ├── matrix.h │ │ │ │ │ └── tensor.h │ │ │ │ ├── eigen.h │ │ │ │ ├── embed.h │ │ │ │ ├── eval.h │ │ │ │ ├── functional.h │ │ │ │ ├── gil.h │ │ │ │ ├── iostream.h │ │ │ │ ├── numpy.h │ │ │ │ ├── operators.h │ │ │ │ ├── options.h │ │ │ │ ├── pybind11.h │ │ │ │ ├── pytypes.h │ │ │ │ ├── stl/ │ │ │ │ │ └── filesystem.h │ │ │ │ ├── stl.h │ │ │ │ └── stl_bind.h │ │ │ ├── noxfile.py │ │ │ ├── pybind11/ │ │ │ │ ├── __init__.py │ │ │ │ ├── __main__.py │ │ │ │ ├── _version.py │ │ │ │ ├── commands.py │ │ │ │ ├── py.typed │ │ │ │ └── setup_helpers.py │ │ │ ├── pyproject.toml │ │ │ ├── setup.cfg │ │ │ ├── setup.py │ │ │ ├── tests/ │ │ │ │ ├── CMakeLists.txt │ │ │ │ ├── conftest.py │ │ │ │ ├── constructor_stats.h │ │ │ │ ├── cross_module_gil_utils.cpp │ │ │ │ ├── cross_module_interleaved_error_already_set.cpp │ │ │ │ ├── eigen_tensor_avoid_stl_array.cpp │ │ │ │ ├── env.py │ │ │ │ ├── extra_python_package/ │ │ │ │ │ ├── pytest.ini │ │ │ │ │ └── test_files.py │ │ │ │ ├── extra_setuptools/ │ │ │ │ │ ├── pytest.ini │ │ │ │ │ └── test_setuphelper.py │ │ │ │ ├── local_bindings.h │ │ │ │ ├── object.h │ │ │ │ ├── pybind11_cross_module_tests.cpp │ │ │ │ ├── pybind11_tests.cpp │ │ │ │ ├── pybind11_tests.h │ │ │ │ ├── pytest.ini │ │ │ │ ├── requirements.txt │ │ │ │ ├── test_async.cpp │ │ │ │ ├── test_async.py │ │ │ │ ├── test_buffers.cpp │ │ │ │ ├── test_buffers.py │ │ │ │ ├── test_builtin_casters.cpp │ │ │ │ ├── test_builtin_casters.py │ │ │ │ ├── test_call_policies.cpp │ │ │ │ ├── test_call_policies.py │ │ │ │ ├── test_callbacks.cpp │ │ │ │ ├── test_callbacks.py │ │ │ │ ├── test_chrono.cpp │ │ │ │ ├── test_chrono.py │ │ │ │ ├── test_class.cpp │ │ │ │ ├── test_class.py │ │ │ │ ├── test_cmake_build/ │ │ │ │ │ ├── CMakeLists.txt │ │ │ │ │ ├── embed.cpp │ │ │ │ │ ├── installed_embed/ │ │ │ │ │ │ └── CMakeLists.txt │ │ │ │ │ ├── installed_function/ │ │ │ │ │ │ └── CMakeLists.txt │ │ │ │ │ ├── installed_target/ │ │ │ │ │ │ └── CMakeLists.txt │ │ │ │ │ ├── main.cpp │ │ │ │ │ ├── subdirectory_embed/ │ │ │ │ │ │ └── CMakeLists.txt │ │ │ │ │ ├── subdirectory_function/ │ │ │ │ │ │ └── CMakeLists.txt │ │ │ │ │ ├── subdirectory_target/ │ │ │ │ │ │ └── CMakeLists.txt │ │ │ │ │ └── test.py │ │ │ │ ├── test_const_name.cpp │ │ │ │ ├── test_const_name.py │ │ │ │ ├── test_constants_and_functions.cpp │ │ │ │ ├── test_constants_and_functions.py │ │ │ │ ├── test_copy_move.cpp │ │ │ │ ├── test_copy_move.py │ │ │ │ ├── test_custom_type_casters.cpp │ │ │ │ ├── test_custom_type_casters.py │ │ │ │ ├── test_custom_type_setup.cpp │ │ │ │ ├── test_custom_type_setup.py │ │ │ │ ├── test_docstring_options.cpp │ │ │ │ ├── test_docstring_options.py │ │ │ │ ├── test_eigen_matrix.cpp │ │ │ │ ├── test_eigen_matrix.py │ │ │ │ ├── test_eigen_tensor.cpp │ │ │ │ ├── test_eigen_tensor.inl │ │ │ │ ├── test_eigen_tensor.py │ │ │ │ ├── test_embed/ │ │ │ │ │ ├── CMakeLists.txt │ │ │ │ │ ├── catch.cpp │ │ │ │ │ ├── external_module.cpp │ │ │ │ │ ├── test_interpreter.cpp │ │ │ │ │ ├── test_interpreter.py │ │ │ │ │ └── test_trampoline.py │ │ │ │ ├── test_enum.cpp │ │ │ │ ├── test_enum.py │ │ │ │ ├── test_eval.cpp │ │ │ │ ├── test_eval.py │ │ │ │ ├── test_eval_call.py │ │ │ │ ├── test_exceptions.cpp │ │ │ │ ├── test_exceptions.h │ │ │ │ ├── test_exceptions.py │ │ │ │ ├── test_factory_constructors.cpp │ │ │ │ ├── test_factory_constructors.py │ │ │ │ ├── test_gil_scoped.cpp │ │ │ │ ├── test_gil_scoped.py │ │ │ │ ├── test_iostream.cpp │ │ │ │ ├── test_iostream.py │ │ │ │ ├── test_kwargs_and_defaults.cpp │ │ │ │ ├── test_kwargs_and_defaults.py │ │ │ │ ├── test_local_bindings.cpp │ │ │ │ ├── test_local_bindings.py │ │ │ │ ├── test_methods_and_attributes.cpp │ │ │ │ ├── test_methods_and_attributes.py │ │ │ │ ├── test_modules.cpp │ │ │ │ ├── test_modules.py │ │ │ │ ├── test_multiple_inheritance.cpp │ │ │ │ ├── test_multiple_inheritance.py │ │ │ │ ├── test_numpy_array.cpp │ │ │ │ ├── test_numpy_array.py │ │ │ │ ├── test_numpy_dtypes.cpp │ │ │ │ ├── test_numpy_dtypes.py │ │ │ │ ├── test_numpy_vectorize.cpp │ │ │ │ ├── test_numpy_vectorize.py │ │ │ │ ├── test_opaque_types.cpp │ │ │ │ ├── test_opaque_types.py │ │ │ │ ├── test_operator_overloading.cpp │ │ │ │ ├── test_operator_overloading.py │ │ │ │ ├── test_pickling.cpp │ │ │ │ ├── test_pickling.py │ │ │ │ ├── test_pytypes.cpp │ │ │ │ ├── test_pytypes.py │ │ │ │ ├── test_sequences_and_iterators.cpp │ │ │ │ ├── test_sequences_and_iterators.py │ │ │ │ ├── test_smart_ptr.cpp │ │ │ │ ├── test_smart_ptr.py │ │ │ │ ├── test_stl.cpp │ │ │ │ ├── test_stl.py │ │ │ │ ├── test_stl_binders.cpp │ │ │ │ ├── test_stl_binders.py │ │ │ │ ├── test_tagbased_polymorphic.cpp │ │ │ │ ├── test_tagbased_polymorphic.py │ │ │ │ ├── test_thread.cpp │ │ │ │ ├── test_thread.py │ │ │ │ ├── test_union.cpp │ │ │ │ ├── test_union.py │ │ │ │ ├── test_virtual_functions.cpp │ │ │ │ ├── test_virtual_functions.py │ │ │ │ ├── valgrind-numpy-scipy.supp │ │ │ │ └── valgrind-python.supp │ │ │ └── tools/ │ │ │ ├── FindCatch.cmake │ │ │ ├── FindEigen3.cmake │ │ │ ├── FindPythonLibsNew.cmake │ │ │ ├── JoinPaths.cmake │ │ │ ├── check-style.sh │ │ │ ├── cmake_uninstall.cmake.in │ │ │ ├── codespell_ignore_lines_from_errors.py │ │ │ ├── libsize.py │ │ │ ├── make_changelog.py │ │ │ ├── pybind11.pc.in │ │ │ ├── pybind11Common.cmake │ │ │ ├── pybind11Config.cmake.in │ │ │ ├── pybind11NewTools.cmake │ │ │ ├── pybind11Tools.cmake │ │ │ ├── pyproject.toml │ │ │ ├── setup_global.py.in │ │ │ └── setup_main.py.in │ │ ├── cvtable/ │ │ │ ├── cvtable.go │ │ │ ├── cvtable_test.go │ │ │ └── testdata/ │ │ │ └── cvtable.conf │ │ ├── go.mod │ │ ├── go.sum │ │ ├── point.go │ │ ├── rect.go │ │ ├── rect_test.go │ │ └── vector/ │ │ ├── vector.go │ │ └── vector_test.go │ ├── grpc-gateway/ │ │ ├── date/ │ │ │ ├── date.pb.go │ │ │ ├── date.pb.gw.go │ │ │ ├── date.proto │ │ │ ├── date.yaml │ │ │ └── date_grpc.pb.go │ │ ├── gateway_handler.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── grpc_gateway.go │ │ ├── grpc_gateway_grpc.option.go │ │ ├── grpc_gateway_http.option.go │ │ ├── grpc_gateway_option.go │ │ └── grpc_gateway_test.go │ ├── logs/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── hook.go │ │ ├── log.go │ │ ├── log.option.go │ │ ├── log.pb.go │ │ ├── log.proto │ │ ├── log.yaml │ │ ├── log_option.go │ │ ├── log_test.go │ │ ├── logrus/ │ │ │ ├── formatter.go │ │ │ ├── glog_formatter.go │ │ │ ├── glog_formatter_test.go │ │ │ ├── terminal_check_bsd.go │ │ │ ├── terminal_check_js.go │ │ │ ├── terminal_check_notappengine.go │ │ │ ├── terminal_check_solaris.go │ │ │ ├── terminal_check_unix.go │ │ │ └── terminal_check_windows.go │ │ └── slog_test.go │ ├── middleware/ │ │ ├── api/ │ │ │ ├── tcloud/ │ │ │ │ └── v3.0/ │ │ │ │ ├── http.interceptor.error.go │ │ │ │ ├── interceptor.error.go │ │ │ │ ├── jsonpb.marshaler.go │ │ │ │ ├── tcloud.pb.go │ │ │ │ └── tcloud.proto │ │ │ └── trivial/ │ │ │ ├── v1/ │ │ │ │ ├── api.pb.go │ │ │ │ ├── api.proto │ │ │ │ ├── http.interceptor.error.go │ │ │ │ └── interceptor.error.go │ │ │ └── v2/ │ │ │ ├── api.pb.go │ │ │ ├── api.proto │ │ │ ├── http.interceptor.error.go │ │ │ └── interceptor.error.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── grpc-middleware/ │ │ │ ├── debug/ │ │ │ │ ├── in_output_printer_client.interceptor.go │ │ │ │ ├── in_output_printer_server.interceptor.go │ │ │ │ └── request_id_server.interceptor.go │ │ │ ├── opentelemetry/ │ │ │ │ ├── metric_server.interceptor.go │ │ │ │ ├── modular_client.interceptor.go │ │ │ │ ├── modular_server.interceptor.go │ │ │ │ ├── trace_client.interceptor.go │ │ │ │ └── trace_server.interceptor.go │ │ │ ├── ratelimit/ │ │ │ │ ├── ratelimit_qps_server.interceptor.go │ │ │ │ └── ratelimit_server.interceptor.go │ │ │ └── timer/ │ │ │ ├── timer_client.interceptor.go │ │ │ └── timer_server.interceptor.go │ │ ├── http-middleware/ │ │ │ ├── cors/ │ │ │ │ ├── cors.go │ │ │ │ └── cors_test.go │ │ │ ├── debug/ │ │ │ │ ├── in.output_printer.go │ │ │ │ ├── in.output_printer_truncate.go │ │ │ │ ├── recoverer.go │ │ │ │ └── request_id.go │ │ │ ├── http/ │ │ │ │ ├── clean_path.go │ │ │ │ ├── strip_prefix.go │ │ │ │ ├── strip_prefix_test.go │ │ │ │ └── timeout.go │ │ │ ├── opentelemetry/ │ │ │ │ ├── metric.interceptor.go │ │ │ │ └── trace.interceptor.go │ │ │ ├── ratelimiter/ │ │ │ │ ├── ratelimiter.go │ │ │ │ └── ratelimiter_qps.go │ │ │ └── timer/ │ │ │ └── timer_server.interceptor.go │ │ ├── local.middleware.wrap.go │ │ └── resource/ │ │ ├── middleware.handler.go │ │ ├── monitor.metrics.go │ │ └── monitor.resource.go │ ├── mq/ │ │ ├── consumer.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── kafka/ │ │ │ ├── config.go │ │ │ ├── config.option.go │ │ │ ├── config_option.go │ │ │ ├── kafka.go │ │ │ ├── kafka.option.go │ │ │ ├── kafka.pb.go │ │ │ ├── kafka.proto │ │ │ ├── kafka.yaml │ │ │ ├── kafka_consumer.go │ │ │ ├── kafka_message.go │ │ │ ├── kafka_option.go │ │ │ ├── kafka_producer.go │ │ │ └── kafka_test.go │ │ ├── message.go │ │ └── producer.go │ ├── opentelemetry/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── metric/ │ │ │ ├── api/ │ │ │ │ ├── api.go │ │ │ │ ├── example_test.go │ │ │ │ └── instrument.go │ │ │ ├── meter.go │ │ │ ├── meter.logging_exporter.go │ │ │ ├── meter.option.go │ │ │ ├── meter.pull.exporter.go │ │ │ ├── meter.push.exporter.go │ │ │ ├── meter_option.go │ │ │ ├── otlp/ │ │ │ │ ├── otlp.metric.go │ │ │ │ ├── otlp.metric.option.go │ │ │ │ └── otlp.metric_option.go │ │ │ ├── prometheus/ │ │ │ │ ├── prometheus.metric.go │ │ │ │ ├── prometheus.metric.option.go │ │ │ │ └── prometheus.metric_option.go │ │ │ ├── report/ │ │ │ │ ├── dimension.go │ │ │ │ └── report.go │ │ │ └── stdout/ │ │ │ ├── stdout.metric.go │ │ │ ├── stdout.metric.option.go │ │ │ └── stdout.metric_option.go │ │ ├── opentelemetry.go │ │ ├── opentelemetry.option.go │ │ ├── opentelemetry.pb.go │ │ ├── opentelemetry.proto │ │ ├── opentelemetry.yaml │ │ ├── opentelemetry_option.go │ │ ├── opentelemetry_test.go │ │ ├── resource/ │ │ │ ├── resource.go │ │ │ ├── resource.memory.go │ │ │ ├── resource.stats.go │ │ │ ├── resource_stats.option.go │ │ │ └── resource_stats_option.go │ │ └── tracer/ │ │ ├── otlp/ │ │ │ ├── otlp.trace.go │ │ │ └── otlp.trace.option.go │ │ ├── stdout/ │ │ │ ├── stdout.trace.go │ │ │ ├── stdout.trace.option.go │ │ │ └── stdout.trace_option.go │ │ ├── tracer.exporter.go │ │ ├── tracer.go │ │ ├── tracer.logging_exporter.go │ │ ├── tracer.option.go │ │ └── tracer_option.go │ ├── pool/ │ │ ├── go.mod │ │ ├── go.sum │ │ ├── instance/ │ │ │ ├── call.go │ │ │ ├── error.go │ │ │ ├── instance.go │ │ │ ├── pool.instance.go │ │ │ ├── pool.instance.option.go │ │ │ ├── pool.instance_option.go │ │ │ ├── pool.instance_test.go │ │ │ └── thread.go │ │ ├── task/ │ │ │ ├── batch_process.go │ │ │ ├── batch_process_test.go │ │ │ ├── pool.go │ │ │ ├── pool.option.go │ │ │ ├── pool_options.go │ │ │ ├── pool_test.go │ │ │ ├── worker.go │ │ │ └── worker_test.go │ │ └── taskqueue/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── pool.go │ │ ├── pool.option.go │ │ ├── pool_option.go │ │ ├── pool_test.go │ │ ├── queue/ │ │ │ ├── message.go │ │ │ ├── queue.go │ │ │ └── redis/ │ │ │ └── queue.redis.go │ │ ├── redis.yaml │ │ ├── registry.go │ │ ├── task.go │ │ ├── tasker_syncmap.go │ │ ├── taskq.yaml │ │ ├── taskqueue.pb.go │ │ └── taskqueue.proto │ ├── profile/ │ │ ├── go.mod │ │ ├── go.sum │ │ ├── profile.go │ │ └── profile_test.go │ ├── protobuf/ │ │ ├── go.mod │ │ ├── go.sum │ │ ├── jsonpb/ │ │ │ ├── jsonpb_marshal.go │ │ │ └── jsonpb_unmarshal.go │ │ └── prototext/ │ │ └── encode.go │ ├── proxy/ │ │ ├── go.mod │ │ ├── go.sum │ │ ├── proxy.go │ │ ├── proxy.option.go │ │ ├── proxy_option.go │ │ └── proxy_test.go │ ├── resolver/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── dns/ │ │ │ ├── dns_resolver.go │ │ │ ├── k8s-resolver/ │ │ │ │ ├── k8s_dns_resolver.go │ │ │ │ ├── k8s_dns_resolver_test.go │ │ │ │ ├── k8s_resolver.option.go │ │ │ │ └── k8s_resolver_option.go │ │ │ └── net-resolver/ │ │ │ └── net_dns_resolver.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── resolver.go │ │ ├── resolver.pb.go │ │ ├── resolver.proto │ │ ├── resolver.yaml │ │ ├── resolver_query.option.go │ │ ├── resolver_query_option.go │ │ ├── resolver_test.go │ │ └── resolverquerymap_syncmap.go │ ├── scheduler/ │ │ ├── backend/ │ │ │ └── backend.go │ │ ├── broker/ │ │ │ ├── broker.go │ │ │ └── memory/ │ │ │ └── memory.go │ │ ├── dispatcher.go │ │ ├── dispatcher_test.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── server.go │ │ ├── server_test.go │ │ ├── task/ │ │ │ ├── result.go │ │ │ ├── task.go │ │ │ └── validate.go │ │ ├── types/ │ │ │ ├── task.pb.go │ │ │ └── task.proto │ │ └── worker.go │ ├── storage/ │ │ ├── go.mod │ │ ├── go.sum │ │ ├── mount/ │ │ │ ├── mount.go │ │ │ └── mount_test.go │ │ └── s3/ │ │ ├── config.go │ │ ├── config.option.go │ │ ├── config_option.go │ │ ├── s3.go │ │ ├── s3.option.go │ │ ├── s3.pb.go │ │ ├── s3.proto │ │ ├── s3.yaml │ │ ├── s3_option.go │ │ └── s3_test.go │ ├── viper/ │ │ ├── code/ │ │ │ ├── error.template.pb.go │ │ │ └── error.template.proto │ │ ├── error.yaml │ │ ├── go.mod │ │ ├── go.sum │ │ ├── unmarshaler.go │ │ ├── viper.go │ │ └── viper_test.go │ └── webserver/ │ ├── app/ │ │ ├── cmd.go │ │ ├── flags.go │ │ └── version.go │ ├── config.go │ ├── config.option.go │ ├── config_option.go │ ├── controller/ │ │ ├── healthz/ │ │ │ ├── checker.go │ │ │ ├── healthz.go │ │ │ └── healthz_test.go │ │ ├── profiler/ │ │ │ └── profiler.go │ │ └── static/ │ │ ├── static.go │ │ └── static_test.go │ ├── go.mod │ ├── go.sum │ ├── hooks.go │ ├── symbolizer.go │ ├── webserver.go │ ├── webserver.pb.go │ ├── webserver.proto │ ├── webserver.proto.go │ ├── webserver.yaml │ ├── webserver_qps_limit.go │ └── webserver_test.go ├── script/ │ ├── copyright.sh │ ├── copyright.txt │ ├── go_proto_gen.sh │ └── tools/ │ ├── cat.sh │ └── dmesg.sh ├── third_party/ │ ├── README.md │ └── github.com/ │ └── grpc-ecosystem/ │ └── grpc-gateway/ │ └── google/ │ └── api/ │ ├── annotations.proto │ └── http.proto └── tutorial/ └── programming_paradigm/ ├── control.inverse_test.go ├── decorator_test.go ├── error.handle_test.go ├── factory_test.go ├── function.options_test.go ├── interface.check_test.go ├── interface.program_test.go ├── map.reduce_test.go ├── pipeline_test.go └── visitor_test.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ pkg/gocv/cgo/third_path/** linguist-vendored ================================================ FILE: .gitignore ================================================ # # NOTE! Please use 'git ls-files -i --exclude-standard' # command after changing this file, to see if there are # any tracked files which get ignored after the change. # # Temp files (e.g. editors). *~ *.sw[op] # Compiled objects. #*.a *.o *.l[ao] #*.so *.exe *.d !**/tmpfiles.d !crosh/dev.d *.depends .deps .libs *.gch *.gcda *.gcno # Common output files. *.dump *.out *.test # Protobuf files. # *.pb.cc # *.pb.h # Python files. *.pyc # Debug (e.g. gdb). .gdb_history .gdbinit # xxx.core file *.core cscope.* tags tags_sorted_by_file # Patch files. *.diff *.patch *.orig *.rej # Nested git repos. /glbench/images/ # Cargo lock file. Cargo.lock # Cargo build directories. target/ # VSCode source dirs .vscode/ # Intellij project dirs .idea # clangd cache dir .clangd .cache # Other .DS_Store ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2020 kay 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. ================================================ FILE: README.md ================================================ # golang Golang lib is a comprehensive programming toolkit for building microservices in Go. It provides a rich set of interfaces and services to accelerate your development. ## Overview This library offers a complete set of tools and utilities for developing Go microservices, including web servers, database connections, message queues, service discovery, monitoring, logging, and much more. It's designed to speed up development by providing production-ready components with sensible defaults. ## Features ### Core Components - **Web Server** (`pkg/webserver`): High-performance web server built on Gin and gRPC-Gateway - HTTP and gRPC support - Graceful shutdown - Health checks and profiling endpoints - Service registry integration (Consul) - Request/response middleware - **Configuration** (`pkg/viper`, `pkg/config`): Flexible configuration management - Viper integration for YAML/JSON/TOML configs - Environment variable support - Configuration validation - **Logging** (`pkg/logs`): Advanced logging capabilities - Logrus-based logging - Log rotation (size/time-based) - Context-aware logging with request IDs - Multiple output formats (JSON, text) - **Database** (`pkg/database`): Database connectivity - MySQL support with connection pooling - Redis client with advanced features - Transaction management - **Message Queue** (`pkg/mq`): Message queue integration - Kafka producer and consumer - Batch processing - Error handling and retry mechanisms - **Service Discovery** (`pkg/discovery`): Service registration and discovery - Consul integration - Etcd support - Health check integration - **Monitoring** (`pkg/monitor`): Observability tools - OpenTelemetry integration - Prometheus metrics - Distributed tracing - **Middleware** (`pkg/middleware`): HTTP and gRPC middleware - Authentication/Authorization - Rate limiting - Request logging - Error handling - **Storage** (`pkg/storage`): Object storage support - S3-compatible storage - File mount utilities - **Task Management** (`pkg/scheduler`, `pkg/crontab`, `pkg/pool`): - Task scheduler - Cron job support - Connection and task pools - Work queues - **File Operations**: - File rotation (`pkg/file-rotate`) - File transfer (`pkg/file-transfer`) - File cleanup (`pkg/file-cleanup`) - File system monitoring (`pkg/fsnotify`) - **gRPC Gateway** (`pkg/grpc-gateway`): RESTful API gateway for gRPC services - **DNS Resolver** (`pkg/resolver`): Advanced DNS resolution with caching - **Binary Log** (`pkg/binlog`): Binary log management for data replication - **Other Utilities**: - Proxy support (`pkg/proxy`) - Performance profiling (`pkg/profile`) - Protobuf utilities (`pkg/protobuf`) - OpenCV bindings (`pkg/gocv`) ### Standard Library Enhancements (`go/`) The `go/` directory contains enhanced versions of standard library packages with additional functionality: - **Context**: Request ID extraction and propagation - **Errors**: Structured error handling with codes - **Time**: Exponential backoff, rate limiting, time utilities - **Net**: gRPC/HTTP clients, DNS resolver, IP/MAC utilities - **Crypto**: AES, MD5, SHA256 utilities - **IO**: File operations, copy utilities - **Reflect**: Advanced reflection utilities - **Container**: Heap, Set, WorkQueue data structures - **And more...** ### Tutorials (`tutorial/`) Programming paradigm examples including: - Function options pattern - Decorator pattern - Factory pattern - Error handling patterns - Pipeline pattern - Visitor pattern - And more... ## Quick Start ### Installation ```bash go get github.com/kaydxh/golang ``` ### Basic Web Server Example ```go package main import ( "context" "testing" viper_ "github.com/kaydxh/golang/pkg/viper" webserver_ "github.com/kaydxh/golang/pkg/webserver" ) func main() { cfgFile := "./webserver.yaml" config := webserver_.NewConfig(webserver_.WithViper(viper_.GetViper(cfgFile, "web"))) s, err := config.Complete().New(context.Background()) if err != nil { panic(err) } // Install your web handlers s.InstallWebHandlers(/* your handlers */) prepared, err := s.PrepareRun() if err != nil { panic(err) } prepared.Run(context.Background()) } ``` ### Configuration Example Create a `webserver.yaml` file: ```yaml web: bind_address: host: 0.0.0.0 port: 10000 grpc: max_concurrency_unary: 0 max_concurrency_stream: 0 max_receive_message_size: 0 max_send_message_size: 0 timeout: 0s http: max_concurrency: 0 timeout: 0s debug: enable_profiling: true monitor: open_telemetry: enabled: true metric_collect_duration: 60s otel_trace_exporter_type: trace_stdout otel_metric_exporter_type: metric_stdout ``` ## Package Structure ``` golang/ ├── go/ # Standard library enhancements ├── pkg/ # Main packages │ ├── webserver/ # Web server framework │ ├── logs/ # Logging │ ├── database/ # Database clients │ ├── mq/ # Message queues │ ├── discovery/ # Service discovery │ ├── monitor/ # Monitoring │ └── ... # Other packages ├── tutorial/ # Programming examples └── script/ # Utility scripts ``` ## Requirements - Go 1.24.0 or higher - See `go.mod` for specific dependency versions ## Documentation - Each package contains detailed documentation - Check `tutorial/` directory for usage examples - Review package-level comments for API documentation ## Contributing If you need support, start with your branch, and create a pull request for us. We appreciate your help! ### Development Guidelines 1. Follow Go coding standards 2. Add tests for new features 3. Update documentation 4. Ensure backward compatibility when possible ## License See [LICENSE](LICENSE) file for details. ## Evolution Golang started in Oct 8, 2020. ## Related Projects This library is designed to work seamlessly with: - Gin web framework - gRPC - Consul - Etcd - Kafka - Prometheus - OpenTelemetry ## Support For issues, questions, or contributions, please open an issue or pull request on GitHub. ================================================ FILE: doc/health_check_design.md ================================================ # 健康检查增强功能设计文档 ## 1. 概述 本文档描述了 golang 库中健康检查(Health Check)功能的设计思路和实现细节。该功能提供了 Kubernetes 兼容的健康检查端点,支持存活探针(Liveness)和就绪探针(Readiness),并具备良好的可扩展性。 ## 2. 设计目标 - **Kubernetes 兼容**:支持标准的 `/healthz`、`/livez`、`/readyz` 端点 - **可扩展性**:通过接口抽象支持自定义健康检查器 - **组合能力**:支持聚合多个检查器,统一管理 - **优雅关闭**:关闭时先标记不就绪,允许负载均衡器排空连接 - **可观测性**:提供详细模式,返回每个检查器的状态和延迟 ## 3. 架构设计 ### 3.1 整体架构 ``` ┌─────────────────────────────────────────────────────────────┐ │ WebServer │ │ ┌───────────────────────────────────────────────────────┐ │ │ │ HealthzController │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ │ │ livezCheckers │ │ readyzCheckers │ │ │ │ │ │ (Composite) │ │ (Composite) │ │ │ │ │ │ ┌───────────┐ │ │ ┌───────────┐ │ │ │ │ │ │ │ Ping │ │ │ │ HTTP │ │ │ │ │ │ │ ├───────────┤ │ │ ├───────────┤ │ │ │ │ │ │ │ TCP │ │ │ │ TCP │ │ │ │ │ │ │ ├───────────┤ │ │ ├───────────┤ │ │ │ │ │ │ │ Custom │ │ │ │ Custom │ │ │ │ │ │ │ └───────────┘ │ │ └───────────┘ │ │ │ │ │ └─────────────────┘ └─────────────────┘ │ │ │ └───────────────────────────────────────────────────────┘ │ │ │ │ HTTP Endpoints: │ │ - GET /healthz 综合健康检查 │ │ - GET /livez 存活探针 │ │ - GET /readyz 就绪探针 │ │ - GET /healthz/verbose 详细健康检查结果 │ │ - GET /livez/verbose 详细存活检查结果 │ │ - GET /readyz/verbose 详细就绪检查结果 │ └─────────────────────────────────────────────────────────────┘ ``` ### 3.2 核心组件 | 组件 | 职责 | |------|------| | `HealthChecker` | 健康检查器接口,定义检查行为 | | `CompositeHealthChecker` | 组合检查器,聚合多个检查器 | | `Controller` | 健康检查控制器,管理端点和检查逻辑 | | `WebServer` | 集成健康检查控制器,处理生命周期 | ## 4. 核心接口设计 ### 4.1 HealthChecker 接口 ```go // HealthChecker 是健康检查的核心接口 type HealthChecker interface { // Name 返回检查器名称,用于日志和详细结果展示 Name() string // Check 执行健康检查,返回 nil 表示健康,返回 error 表示不健康 Check(ctx context.Context) error } ``` ### 4.2 内置检查器实现 | 检查器类型 | 用途 | 实现要点 | |-----------|------|---------| | `PingHealthChecker` | 基础检查,始终返回健康 | 用于默认存活检查 | | `HTTPHealthChecker` | HTTP 端点健康检查 | 检查状态码 200-299 | | `TCPHealthChecker` | TCP 端口连通性检查 | 使用 `net.Dialer` | | `FuncHealthChecker` | 函数包装器 | 支持自定义检查逻辑 | | `CompositeHealthChecker` | 组合检查器 | 聚合多个检查器 | ## 5. 关键实现 ### 5.1 HTTP 健康检查器 ```go type HTTPHealthChecker struct { name string url string timeout time.Duration client *http.Client } func (h *HTTPHealthChecker) Check(ctx context.Context) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.url, nil) if err != nil { return fmt.Errorf("failed to create request: %w", err) } resp, err := h.client.Do(req) if err != nil { return fmt.Errorf("failed to connect: %w", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("unhealthy status code: %d", resp.StatusCode) } return nil } ``` ### 5.2 TCP 健康检查器 ```go type TCPHealthChecker struct { name string addr string timeout time.Duration } func (t *TCPHealthChecker) Check(ctx context.Context) error { dialer := &net.Dialer{Timeout: t.timeout} conn, err := dialer.DialContext(ctx, "tcp", t.addr) if err != nil { return fmt.Errorf("failed to connect to %s: %w", t.addr, err) } conn.Close() return nil } ``` ### 5.3 组合健康检查器 ```go type CompositeHealthChecker struct { name string mu sync.RWMutex checkers []HealthChecker } func (c *CompositeHealthChecker) Check(ctx context.Context) error { c.mu.RLock() defer c.mu.RUnlock() for _, checker := range c.checkers { if err := checker.Check(ctx); err != nil { return fmt.Errorf("%s: %w", checker.Name(), err) } } return nil } // AddChecker 线程安全地添加检查器 func (c *CompositeHealthChecker) AddChecker(checker HealthChecker) { c.mu.Lock() defer c.mu.Unlock() c.checkers = append(c.checkers, checker) } ``` ### 5.4 健康检查控制器 ```go type Controller struct { livezCheckers *CompositeHealthChecker // 存活检查器 readyzCheckers *CompositeHealthChecker // 就绪检查器 ready atomic.Bool // 就绪状态 checkTimeout time.Duration // 检查超时(默认 10s) } // Healthz 综合健康检查端点 func (c *Controller) Healthz() gin.HandlerFunc { return func(ctx *gin.Context) { checkCtx, cancel := context.WithTimeout(ctx.Request.Context(), c.checkTimeout) defer cancel() // 检查存活状态 if err := c.livezCheckers.Check(checkCtx); err != nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{ "status": "unhealthy", "type": "livez", "error": err.Error(), }) return } // 检查就绪状态 if !c.ready.Load() { ctx.JSON(http.StatusServiceUnavailable, gin.H{ "status": "not ready", "type": "readyz", "error": "server is shutting down", }) return } if err := c.readyzCheckers.Check(checkCtx); err != nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{ "status": "not ready", "type": "readyz", "error": err.Error(), }) return } ctx.String(http.StatusOK, "ok") } } ``` ## 6. 优雅关闭设计 ### 6.1 关闭流程 ``` 收到关闭信号 (ctx.Done()) │ ▼ 标记服务为不就绪 (SetReady(false)) │ ▼ /readyz 开始返回 503 │ ▼ 等待 ShutdownDelayDuration (允许 LB 排空连接) │ ▼ 关闭 HTTP/gRPC 服务器 ``` ### 6.2 实现代码 ```go func (s preparedGenericWebServer) Run(ctx context.Context) error { // ... 启动代码 ... <-ctx.Done() // 等待关闭信号 // 1. 标记服务器为不就绪 if s.HealthzController != nil { s.HealthzController.SetReady(false) } // 2. 等待关闭延迟,允许负载均衡器排空连接 if s.ShutdownDelayDuration > 0 { time.Sleep(s.ShutdownDelayDuration) } // 3. 关闭服务器 // ... } ``` ## 7. 与 Consul 服务发现集成 ```go func (srv *ServiceRegistryServer) Register() error { checkUrl := fmt.Sprintf("http://%v:%v/api/%v/v1/health", srv.Ip, srv.Port, srv.ServiceName) reg := &api.AgentServiceRegistration{ ID: srv.ServiceId, Name: srv.ServiceName, Check: &api.AgentServiceCheck{ Interval: srv.CheckInterval.String(), HTTP: checkUrl, DeregisterCriticalServiceAfter: srv.TTL.String(), }, } return agent.ServiceRegister(reg) } ``` ## 8. 使用示例 ### 8.1 添加自定义检查器 ```go // 添加数据库健康检查 dbChecker := healthz.NewTCPHealthChecker("mysql", "localhost:3306", 5*time.Second) server.HealthzController.AddReadyzChecker(dbChecker) // 添加 Redis 健康检查 redisChecker := healthz.NewTCPHealthChecker("redis", "localhost:6379", 5*time.Second) server.HealthzController.AddReadyzChecker(redisChecker) // 添加自定义检查逻辑 customChecker := healthz.NewFuncHealthChecker("custom", func(ctx context.Context) error { // 自定义检查逻辑 if someCondition { return errors.New("unhealthy") } return nil }) server.HealthzController.AddLivezChecker(customChecker) ``` ### 8.2 Kubernetes 部署配置 ```yaml apiVersion: v1 kind: Pod spec: containers: - name: app livenessProbe: httpGet: path: /livez port: 8080 initialDelaySeconds: 10 periodSeconds: 10 readinessProbe: httpGet: path: /readyz port: 8080 initialDelaySeconds: 5 periodSeconds: 5 ``` ## 9. API 响应格式 ### 9.1 健康状态正常 ``` GET /healthz Response: 200 OK Body: ok ``` ### 9.2 健康状态异常 ``` GET /healthz Response: 503 Service Unavailable Body: {"status": "unhealthy", "type": "livez", "error": "mysql: connection refused"} ``` ### 9.3 详细检查结果 ``` GET /healthz/verbose Response: 200 OK Body: { "status": "ok", "livez": { "status": "ok", "checks": [ {"name": "ping", "status": "ok", "latency": "0.1ms"} ] }, "readyz": { "status": "ok", "checks": [ {"name": "mysql", "status": "ok", "latency": "2.3ms"}, {"name": "redis", "status": "ok", "latency": "1.1ms"} ] } } ``` ## 10. 设计特点总结 | 特点 | 说明 | |------|------| | Kubernetes 兼容 | 支持标准的存活/就绪探针端点 | | 可扩展性 | 通过接口支持自定义检查器 | | 组合模式 | 支持聚合多个检查器 | | 详细模式 | 提供每个检查器的详细结果和延迟 | | 优雅关闭 | 关闭时先标记不就绪 | | 超时控制 | 默认 10 秒检查超时,可配置 | | 线程安全 | 使用互斥锁和原子操作保证并发安全 | | 服务发现集成 | 支持 Consul HTTP 健康检查 | ## 11. 文件结构 ``` pkg/webserver/controller/healthz/ ├── checker.go # 健康检查器接口和实现 ├── healthz.go # 健康检查控制器 └── healthz_test.go # 单元测试 pkg/webserver/ ├── webserver.go # WebServer 集成健康检查 └── config.go # 配置和初始化 pkg/discovery/consul/ └── discovery.go # Consul 服务注册健康检查 ``` ================================================ FILE: doc/opentelemetry_design.md ================================================ # OpenTelemetry 监控设计文档 ## 1. 概述 本文档描述了 golang 库中 OpenTelemetry 监控功能的设计思路和实现细节。该功能提供统一的可观测性能力,支持 **Metrics(指标)**、**Traces(链路追踪)** 和 **Logs(日志)**,并支持多种后端导出器(Prometheus、Jaeger、OTLP 等)。 ## 2. 设计目标 - **统一的可观测性**:通过 OpenTelemetry 标准实现 Metrics、Traces、Logs 的统一采集 - **多后端支持**:支持 Prometheus、Jaeger、OTLP、Stdout 等多种导出器 - **腾讯云兼容**:支持腾讯云 Prometheus Remote Write 接入 - **配置驱动**:通过 YAML 配置文件灵活配置各种导出器 - **低侵入性**:通过中间件自动采集 gRPC/HTTP 请求指标和链路追踪 ## 3. 架构设计 ### 3.1 整体架构 ``` ┌─────────────────────────────────────────────────────────────────────────┐ │ 应用层 │ │ ┌───────────────────────────────────────────────────────────────────┐ │ │ │ gRPC/HTTP Server │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ ┌───────────────┐ │ │ │ │ │ Metric 中间件 │ │ Trace 中间件 │ │ 业务代码 │ │ │ │ │ └────────┬────────┘ └────────┬────────┘ └───────────────┘ │ │ │ └───────────│──────────────────────│────────────────────────────────┘ │ └──────────────│──────────────────────│──────────────────────────────────┘ │ │ ▼ ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ OpenTelemetry SDK 层 │ │ ┌───────────────────────────────────────────────────────────────────┐ │ │ │ OpenTelemetryService │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ │ │ MeterProvider │ │ TracerProvider │ │ │ │ │ │ ┌───────────┐ │ │ ┌───────────┐ │ │ │ │ │ │ │ Reader │ │ │ │ Exporter │ │ │ │ │ │ │ └───────────┘ │ │ └───────────┘ │ │ │ │ │ └─────────────────┘ └─────────────────┘ │ │ │ └───────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────┘ │ │ ▼ ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ 导出器层 (Exporter) │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Prometheus │ │ OTLP │ │ Jaeger │ │ Stdout │ │ │ │ (Pull) │ │ (Push) │ │ (Push) │ │ (Push) │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ └─────────│────────────────│────────────────│────────────────│──────────┘ │ │ │ │ ▼ ▼ ▼ ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ 后端存储层 │ │ ┌─────────────┐ ┌─────────────────────┐ ┌─────────────┐ │ │ │ Prometheus │ │ 腾讯云 Prometheus │ │ Jaeger │ │ │ │ Server │ │ Remote Write │ │ Server │ │ │ └─────────────┘ └─────────────────────┘ └─────────────┘ │ └─────────────────────────────────────────────────────────────────────────┘ ``` ### 3.2 核心组件 | 组件 | 职责 | |------|------| | `OpenTelemetryService` | 统一管理 Meter 和 Tracer 的生命周期 | | `MeterProvider` | 管理指标的采集和导出 | | `TracerProvider` | 管理链路追踪的采集和导出 | | `PullExporter` | Pull 模式导出器(如 Prometheus) | | `PushExporter` | Push 模式导出器(如 OTLP、Jaeger、Stdout) | | `ResourceStatsService` | 资源统计服务(CPU、内存等) | ## 4. 指标采集模式 ### 4.1 Pull 模式 vs Push 模式 ``` ┌─────────────────────────────────────────────────────────────────────────┐ │ Pull 模式 (Prometheus) │ │ │ │ ┌─────────────┐ ┌─────────────────────┐ │ │ │ 服务 │ ──────── /metrics ───────→ │ Prometheus │ │ │ │ (暴露端口) │ ←─────── 主动抓取 ────────│ Server │ │ │ └─────────────┘ └─────────────────────┘ │ │ │ │ 特点:服务暴露端口,Prometheus 主动拉取 │ │ 适用:同 VPC、K8s 内部、ServiceMonitor │ └─────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────┐ │ Push 模式 (OTLP) │ │ │ │ ┌─────────────┐ ┌─────────────────────┐ │ │ │ 服务 │ ──────── 主动推送 ───────→ │ 腾讯云 Prometheus │ │ │ │ (定时推送) │ │ Remote Write │ │ │ └─────────────┘ └─────────────────────┘ │ │ │ │ 特点:服务主动推送,无需暴露端口 │ │ 适用:跨 VPC、公网、防火墙限制场景 │ └─────────────────────────────────────────────────────────────────────────┘ ``` ### 4.2 模式对比 | 特性 | Pull 模式 (Prometheus) | Push 模式 (OTLP) | |------|------------------------|------------------| | **数据流向** | 后端主动拉取服务 | 服务主动推送到后端 | | **端口暴露** | 需要暴露 `/metrics` 端点 | 无需暴露端口 | | **网络要求** | Prometheus 需能访问服务 | 服务需能访问采集端 | | **适用场景** | 同 VPC、K8s ServiceMonitor | 跨 VPC、无法暴露端口 | | **配置类型** | `metric_prometheus` | `metric_otlp` | | **Exporter** | `WithMeterPullExporter` | `WithMeterPushExporter` | ### 4.3 选择建议 | 场景 | 推荐模式 | 原因 | |------|---------|------| | K8s 集群内部 | Pull (Prometheus) | Prometheus Operator 原生支持 ServiceMonitor | | 同 VPC 部署 | Pull (Prometheus) | 网络直连,配置简单 | | 跨 VPC / 公网 | Push (OTLP) | 无需暴露端口,穿透防火墙 | | 边缘节点 | Push (OTLP) | 边缘网络不稳定,主动推送更可靠 | | 腾讯云托管 Prometheus | 两者皆可 | 根据网络拓扑选择 | ## 5. 配置设计 ### 5.1 配置结构 (Proto 定义) ```protobuf message OpenTelemetry { bool enabled = 1; google.protobuf.Duration metric_collect_duration = 2; // 指标采集周期 OtelTraceExporterType otel_trace_exporter_type = 3; // 链路导出器类型 OtelMetricExporterType otel_metric_exporter_type = 4; // 指标导出器类型 OtelLogExporterType otel_log_exporter_type = 5; // 日志导出器类型 OtelMetricExporter otel_metric_exporter = 6; // 指标导出器配置 OtelTraceExporter otel_trace_exporter = 7; // 链路导出器配置 Resource resource = 8; // 资源标识 } // 指标导出器配置 message OtelMetricExporter { Prometheus prometheus = 1; // Prometheus Pull 模式 Stdout stdout = 2; // 标准输出 OTLP otlp = 3; // OTLP Push 模式 } // OTLP 导出器配置 message OTLP { string endpoint = 1; // 目标地址 string token = 2; // 认证 Token string protocol = 3; // 协议:http 或 grpc bool insecure = 4; // 是否禁用 TLS map headers = 5; // 自定义请求头 string url_path = 6; // HTTP URL 路径 } ``` ### 5.2 导出器类型枚举 ```protobuf enum OtelMetricExporterType { metric_none = 0; // 不启用 metric_prometheus = 1; // Prometheus Pull 模式 metric_stdout = 2; // 标准输出 metric_otlp = 3; // OTLP Push 模式 } enum OtelTraceExporterType { trace_none = 0; // 不启用 trace_jaeger = 1; // Jaeger trace_stdout = 2; // 标准输出 trace_otlp = 3; // OTLP Push 模式 } ``` ### 5.3 配置示例 #### Prometheus Pull 模式(同 VPC) ```yaml open_telemetry: enabled: true metric_collect_duration: 60s otel_metric_exporter_type: metric_prometheus otel_trace_exporter_type: trace_jaeger otel_metric_exporter: prometheus: url: /metrics # 暴露的端点路径 otel_trace_exporter: jaeger: url: http://jaeger:14268/api/traces resource: service_name: "my-service" attrs: env: "production" ``` #### OTLP Push 模式(腾讯云 Prometheus) ```yaml open_telemetry: enabled: true metric_collect_duration: 60s otel_metric_exporter_type: metric_otlp otel_trace_exporter_type: trace_stdout otel_metric_exporter: otlp: # 腾讯云 Prometheus Remote Write 地址(从控制台获取) endpoint: "your-instance.tencentcloudprom.com" # 认证 Token(从控制台获取) token: "your-prometheus-token" # 协议:http 或 grpc protocol: "http" # 内网访问可设为 true,公网访问设为 false insecure: false # OTLP 默认路径 url_path: "/v1/metrics" resource: service_name: "my-service" attrs: env: "production" region: "ap-guangzhou" ``` ## 6. 核心实现 ### 6.1 OTLP Exporter 实现 ```go // OTLPExporterBuilder OTLP 导出器构建器 type OTLPExporterBuilder struct { opts struct { endpoint string // 目标地址 headers map[string]string // 请求头 timeout time.Duration // 超时时间 insecure bool // 是否禁用 TLS protocol Protocol // 协议类型 urlPath string // URL 路径 } } // Protocol 协议类型 type Protocol int const ( ProtocolHTTP Protocol = iota // HTTP 协议 ProtocolGRPC // gRPC 协议 ) // Build 构建 OTLP Exporter func (b *OTLPExporterBuilder) Build(ctx context.Context) (metric.Exporter, error) { switch b.opts.protocol { case ProtocolHTTP: return b.buildHTTPExporter(ctx) case ProtocolGRPC: return b.buildGRPCExporter(ctx) default: return b.buildHTTPExporter(ctx) } } // buildHTTPExporter 构建 HTTP 导出器 func (b *OTLPExporterBuilder) buildHTTPExporter(ctx context.Context) (metric.Exporter, error) { opts := []otlpmetrichttp.Option{ otlpmetrichttp.WithEndpoint(b.opts.endpoint), } if b.opts.insecure { opts = append(opts, otlpmetrichttp.WithInsecure()) } if len(b.opts.headers) > 0 { opts = append(opts, otlpmetrichttp.WithHeaders(b.opts.headers)) } if b.opts.timeout > 0 { opts = append(opts, otlpmetrichttp.WithTimeout(b.opts.timeout)) } if b.opts.urlPath != "" { opts = append(opts, otlpmetrichttp.WithURLPath(b.opts.urlPath)) } return otlpmetrichttp.New(ctx, opts...) } ``` ### 6.2 配置加载实现 ```go func (c *completedConfig) installMeter(ctx context.Context) ([]OpenTelemetryServiceOption, error) { var opts []OpenTelemetryServiceOption // 设置采集周期 collectDuration := c.Proto.GetMetricCollectDuration().AsDuration() if collectDuration > 0 { opts = append(opts, WithMetricCollectDuration(collectDuration)) } metricType := c.Proto.OtelMetricExporterType switch metricType { case OtelMetricExporterType_metric_prometheus: // Pull 模式:Prometheus 主动抓取 builder := prometheus_.NewPrometheusExporterBuilder( prometheus_.WithMetricUrlPath(c.Proto.GetOtelMetricExporter().GetPrometheus().GetUrl()), ) opts = append(opts, WithMeterPullExporter(builder)) case OtelMetricExporterType_metric_otlp: // Push 模式:服务主动推送 otlpConfig := c.Proto.GetOtelMetricExporter().GetOtlp() var otlpOpts []otlpmetric_.OTLPExporterBuilderOption // 配置 endpoint if otlpConfig.GetEndpoint() != "" { otlpOpts = append(otlpOpts, otlpmetric_.WithEndpoint(otlpConfig.GetEndpoint())) } // 配置协议 if otlpConfig.GetProtocol() == "grpc" { otlpOpts = append(otlpOpts, otlpmetric_.WithProtocol(otlpmetric_.ProtocolGRPC)) } else { otlpOpts = append(otlpOpts, otlpmetric_.WithProtocol(otlpmetric_.ProtocolHTTP)) } // 配置认证头 headers := make(map[string]string) for k, v := range otlpConfig.GetHeaders() { headers[k] = v } if otlpConfig.GetToken() != "" { headers["Authorization"] = "Bearer " + otlpConfig.GetToken() } if len(headers) > 0 { otlpOpts = append(otlpOpts, otlpmetric_.WithHeaders(headers)) } builder := otlpmetric_.NewOTLPExporterBuilder(otlpOpts...) opts = append(opts, WithMeterPushExporter(builder)) case OtelMetricExporterType_metric_stdout: // 标准输出(调试用) builder := stdoutmetric_.NewStdoutExporterBuilder( stdoutmetric_.WithPrettyPrint(c.Proto.GetOtelMetricExporter().GetStdout().GetPrettyPrint()), ) opts = append(opts, WithMeterPushExporter(builder)) } return opts, nil } ``` ### 6.3 中间件集成 #### gRPC 指标拦截器 ```go // UnaryServerInterceptorOfMetric gRPC 一元调用指标拦截器 func UnaryServerInterceptorOfMetric() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { start := time.Now() resp, err := handler(ctx, req) duration := time.Since(start) // 记录请求指标 meter_.RecordRequest(ctx, info.FullMethod, duration, err) return resp, err } } ``` #### HTTP 指标中间件 ```go // MetricMiddleware HTTP 指标中间件 func MetricMiddleware() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() c.Next() duration := time.Since(start) // 记录请求指标 meter_.RecordHTTPRequest(c.Request.Context(), c.Request.Method, c.Request.URL.Path, c.Writer.Status(), duration) } } ``` ## 7. 腾讯云 Prometheus 接入指南 ### 7.1 获取配置信息 1. 登录 [腾讯云 Prometheus 监控控制台](https://console.cloud.tencent.com/monitor/prometheus) 2. 选择对应实例,进入**基本信息** > **服务地址** 3. 获取以下信息: - **Remote Write 地址**:填入 `endpoint` - **Token**:填入 `token` ### 7.2 配置参数说明 | 参数 | 说明 | 示例 | |------|------|------| | `endpoint` | Remote Write 地址(不含 https://) | `your-instance.tencentcloudprom.com` | | `token` | 认证 Token | `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` | | `protocol` | 传输协议 | `http`(推荐)或 `grpc` | | `insecure` | 是否禁用 TLS | 同 VPC 可用 `true`,公网用 `false` | | `url_path` | OTLP URL 路径 | `/v1/metrics` | ### 7.3 完整配置示例 ```yaml web: monitor: open_telemetry: enabled: true metric_collect_duration: 60s otel_metric_exporter_type: metric_otlp otel_trace_exporter_type: trace_stdout otel_metric_exporter: otlp: endpoint: "your-instance.tencentcloudprom.com" token: "your-prometheus-token" protocol: "http" insecure: false url_path: "/v1/metrics" resource: service_name: "sea-date" attrs: env: "production" region: "ap-guangzhou" ``` ## 8. K8s Resource 属性 ### 8.1 概述 自动从 K8s 环境变量中采集容器运行时信息,作为 OpenTelemetry Resource 属性注入到所有 Metrics 和 Traces 中。 ### 8.2 支持的 K8s 属性 | 环境变量 | 属性名 | 说明 | |----------|--------|------| | `NODE_IP` | `k8s.node.ip` | 宿主机节点 IP | | `POD_NAMESPACE` | `k8s.namespace.name` | Pod 命名空间 | | `POD_NAME` | `k8s.pod.name` | Pod 名称 | | `POD_IP` | `k8s.pod.ip` | Pod IP | | `CONTAINER_NAME` | `k8s.container.name` | 容器名称 | | `CONTAINER_PLATFORM` | `k8s.container.platform` | 容器平台 (STKE/TKE) | ### 8.3 K8s Deployment 配置示例 ```yaml spec: containers: - name: my-app env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP - name: POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: POD_IP valueFrom: fieldRef: fieldPath: status.podIP - name: CONTAINER_NAME value: "my-app" - name: CONTAINER_PLATFORM value: "STKE" ``` ### 8.4 YAML 配置 ```yaml open_telemetry: resource: service_name: "my-service" service_version: "1.0.0" attrs: env: "production" k8s: enabled: true # 是否启用 K8s 属性自动检测(默认 true) # 以下属性会自动从环境变量读取,也可以手动覆盖 # node_ip: "" # pod_namespace: "" # pod_name: "" # pod_ip: "" # container_name: "" # container_platform: "" apm: token: "" # APM Token,与业务系统关联,从 APM 控制台获取 ``` ### 8.5 APM Token 配置 #### 概述 APM(Application Performance Management)Token 用于腾讯云 APM 服务的身份认证和数据关联。Token 会作为 Resource attribute 添加到所有 trace span 中。 #### 获取 APM Token 1. 登录 [腾讯云 APM 控制台](https://console.cloud.tencent.com/apm/monitor/access) 2. 选择对应业务系统 3. 获取 Token #### YAML 配置 ```yaml open_telemetry: enabled: true resource: service_name: "my-service" apm: token: "your-apm-token" # 从 APM 控制台获取 ``` #### Proto 定义 ```protobuf message Resource { string service_name = 1; string service_version = 2; map attrs = 3; K8sResource k8s = 10; Apm apm = 11; // 腾讯云 APM 配置 ZhiYan zhiyan = 12; // 智研平台配置 } message Apm { string token = 1; // APM Token,与业务系统关联 } message ZhiYan { string app_mark = 1; // 业务指标上报 appMark string global_app_mark = 2; // 全局指标上报 appMark string env = 3; // 环境标识 (prod/test/dev) string instance_mark = 4; // 实例标识 string zhiyan_apm_token = 5; // 智研 APM Token string expand_key = 6; // 是否扩展属性到维度 } ``` #### 核心实现 ```go // APM Token key var ApmTokenKey = attribute.Key("token") // WithApmToken 设置 APM Token func WithApmToken(token string) ResourceOption { return func(o *ResourceOptions) { o.ApmToken = token } } // 在 NewResource 中添加 APM Token if options.ApmToken != "" { attrs = append(attrs, ApmTokenKey.String(options.ApmToken)) } ``` ### 8.6 智研 (ZhiYan) 平台配置 #### 概述 智研是腾讯内部的可观测平台,支持 Metrics、Traces、Logs 的统一上报和分析。通过 OpenTelemetry 协议接入。 #### 智研 vs 腾讯云 APM 对比 | 平台 | 访问范围 | 认证方式 | 上报地址 | |------|---------|---------|---------| | 腾讯云 APM | 公网 | `Authorization: Bearer ` | `xxx.tencentcloudapi.com` | | 智研平台 | 内网 | `tps.tenant.id` Resource Attribute | `<智研内网trace地址>:4317` | #### 获取智研租户 1. 登录 2. 进入 监控宝 > 应用性能监控 > 接入管理 3. 获取租户信息,格式:`空间ID#日志租户#监控宝租户` - 示例:`<空间ID>#<日志租户>#<监控宝租户>` #### 智研上报地址 | 网络环境 | 类型 | 服务地址 | 协议 | 备注 | |----------|------|---------|------|------| | **内网** | Metric | `<内网metric上报地址>:4318` | HTTP | 推荐,无需 TLS | | **外网** | Metric | `<外网metric上报地址>:4318` | **HTTPS** | 必须启用 TLS | | 内网 | Trace | `<内网trace上报地址>:4317` | gRPC | IDC 内网 | | 内网 | Trace | `<内网trace上报地址>:4318` | HTTP | IDC 内网 | | 公网 | Trace | `<外网trace上报地址>:4317` | gRPC | DevCloud/研发环境 | > **⚠️ 重要**: 外网域名 **必须使用 HTTPS**(`insecure: false`),否则会连接超时。 #### YAML 配置示例 ```yaml open_telemetry: enabled: true # Trace 上报到智研 otel_trace_exporter_type: trace_otlp otel_trace_exporter: otlp: endpoint: "<智研trace上报地址>:4317" protocol: "grpc" insecure: true # Metric 上报到智研 otel_metric_exporter_type: metric_otlp otel_metric_exporter: otlp: endpoint: "<智研metric上报地址>:4317" protocol: "grpc" insecure: true resource: service_name: "my-service" zhiyan: # 业务指标上报 appMark(用于 App MeterProvider) app_mark: "" # 全局指标上报 appMark(用于 Global MeterProvider) global_app_mark: "" # 环境标识 env: "prod" # 智研 APM Token(用于 Trace 上报) # 格式:空间ID#日志租户#监控宝租户 zhiyan_apm_token: "<空间ID>#<日志租户>#<监控宝租户>" # 是否将 resource 属性扩展到指标维度 expand_key: "no" ``` #### 智研 Resource Attribute Keys | Attribute Key | 说明 | 是否必填 | 类型 | |---------------|------|---------|------| | `__zhiyan_app_mark__` | 上报应用标记 | **是** | string | | `__zhiyan_env__` | 环境标识 (prod/test/dev) | **是** | string | | `__zhiyan_instance_mark__` | 上报实例标识 | 否 | string | | `__zhiyan_expand_tag_enable__` | 是否扩展属性到维度 | 否(默认 no) | string | | `__zhiyan_data_grain__` | 数据粒度 (10/30/60) | 否(默认 60) | int | | `__zhiyan_data_type__` | 数据类型,秒级填 "second" | 否 | string | | `tps.tenant.id` | 智研 APM 租户 ID | Trace 上报必填 | string | #### 智研上报必须配置 根据智研对接文档,以下配置项**必须正确设置**: | 配置项 | 要求 | 说明 | |--------|------|------| | Delta Temporality | `temporality_delta: true` | 智研只支持 Delta 时间性 | | Gzip 压缩 | `compression: true` | 建议启用以减少带宽 | | 采集周期 | 与数据粒度一致 | 如分钟级数据设置 60s | | HTTP 端口 | 4318 | OTLP HTTP 标准端口 | #### 核心实现 ```go // 智研平台 attribute keys var ( ZhiYanAppMarkKey = attribute.Key("__zhiyan_app_mark__") ZhiYanInstanceMarkKey = attribute.Key("__zhiyan_instance_mark__") ZhiYanEnvKey = attribute.Key("__zhiyan_env__") ZhiYanExpandKey = attribute.Key("__zhiyan_expand_tag_enable__") ZhiYanDataGrainKey = attribute.Key("__zhiyan_data_grain__") ZhiYanDataTypeKey = attribute.Key("__zhiyan_data_type__") ZhiYanTpsTenantIDKey = attribute.Key("tps.tenant.id") ) // 在 NewResource 中添加智研属性 if options.ZhiYanAppMark != "" { attrs = append(attrs, ZhiYanAppMarkKey.String(options.ZhiYanAppMark)) attrs = append(attrs, ZhiYanEnvKey.String(options.ZhiYanEnv)) attrs = append(attrs, ZhiYanExpandKey.String("no")) } if options.ZhiYanApmToken != "" { attrs = append(attrs, ZhiYanTpsTenantIDKey.String(options.ZhiYanApmToken)) } ``` ### 8.7 核心实现 ```go // K8s 环境变量映射 var k8sEnvToAttribute = map[string]attribute.Key{ "NODE_IP": semconv.K8SNodeNameKey, "POD_NAMESPACE": semconv.K8SNamespaceNameKey, "POD_NAME": semconv.K8SPodNameKey, "POD_IP": attribute.Key("k8s.pod.ip"), "CONTAINER_NAME": semconv.K8SContainerNameKey, "CONTAINER_PLATFORM": attribute.Key("k8s.container.platform"), } // NewResource 创建包含 K8s 属性的 Resource func NewResource(opts ...ResourceOption) (*resource.Resource, error) { cfg := defaultResourceConfig() for _, opt := range opts { opt(cfg) } var attrs []attribute.KeyValue // 添加服务信息 if cfg.serviceName != "" { attrs = append(attrs, semconv.ServiceName(cfg.serviceName)) } if cfg.serviceVersion != "" { attrs = append(attrs, semconv.ServiceVersion(cfg.serviceVersion)) } // 添加 K8s 属性 if cfg.enableK8s { attrs = append(attrs, getK8sAttributes()...) } // 添加自定义属性 for k, v := range cfg.attrs { attrs = append(attrs, attribute.String(k, v)) } return resource.NewWithAttributes(semconv.SchemaURL, attrs...) } ``` ## 9. 模调上报(主/被调) ### 9.1 概述 模调上报是一种标准化的服务调用监控方案,支持: - **被调上报 (P)**:服务端记录被调用的指标 - **主调上报 (A)**:客户端记录调用其他服务的指标 ### 9.2 上报指标 | 指标名 | 类型 | 说明 | |--------|------|------| | `requests` | Counter | 请求数 | | `success` | Counter | 成功数 | | `timeout` | Counter | 超时数 | | `abnormal` | Counter | 异常数 | | `cost` | Counter | 累计耗时(ms) | | `duration` | Histogram | 耗时分布 | ### 9.3 维度属性 #### 被调方 (P) 维度 | 属性 | 说明 | |------|------| | `ret_code` | 返回码 | | `p_ip` | 被调 IP | | `p_app` | 被调应用名 | | `p_server` | 被调服务名 | | `p_service` | 被调 Service | | `p_interface` | 被调接口 | #### 主调方 (A) 维度 | 属性 | 说明 | |------|------| | `a_ip` | 主调 IP | | `a_app` | 主调应用名 | | `a_server` | 主调服务名 | | `a_service` | 主调 Service | | `a_interface` | 主调接口 | ### 9.4 gRPC 拦截器使用示例 #### Server 端(被调上报) ```go import interceptoropentelemetry "github.com/kaydxh/golang/pkg/middleware/grpc-middleware/opentelemetry" server := grpc.NewServer( grpc.ChainUnaryInterceptor( interceptoropentelemetry.UnaryServerModularInterceptor( interceptoropentelemetry.ModularServerConfig{ AppName: "my-app", ServerName: "my-server", }, ), ), grpc.ChainStreamInterceptor( interceptoropentelemetry.StreamServerModularInterceptor( interceptoropentelemetry.ModularServerConfig{ AppName: "my-app", ServerName: "my-server", }, ), ), ) ``` #### Client 端(主调上报) ```go conn, err := grpc.Dial(target, grpc.WithChainUnaryInterceptor( interceptoropentelemetry.UnaryClientModularInterceptor( interceptoropentelemetry.ModularClientConfig{ AppName: "my-app", ServerName: "my-server", ServiceName: "my-service", }, ), ), grpc.WithChainStreamInterceptor( interceptoropentelemetry.StreamClientModularInterceptor( interceptoropentelemetry.ModularClientConfig{ AppName: "my-app", ServerName: "my-server", ServiceName: "my-service", }, ), ), ) ``` ### 9.5 核心实现 ```go // MetricReporter 模调上报器 type MetricReporter struct { meterProvider otelmetric.MeterProvider counters map[string]otelmetric.Int64Counter histograms map[string]otelmetric.Float64Histogram mu sync.RWMutex } // ReportServerMetric 被调上报 func (r *MetricReporter) ReportServerMetric(ctx context.Context, dim *ServerDimension, costMs float64) { attrs := dim.ToAttributes() // 请求数 r.getCounter(ServerReportMeterName, RequestsMetricName).Add(ctx, 1, otelmetric.WithAttributes(attrs...)) // 成功/超时/异常 if dim.IsSuccess() { r.getCounter(ServerReportMeterName, SuccessMetricName).Add(ctx, 1, otelmetric.WithAttributes(attrs...)) } else if dim.IsTimeout() { r.getCounter(ServerReportMeterName, TimeoutMetricName).Add(ctx, 1, otelmetric.WithAttributes(attrs...)) } else { r.getCounter(ServerReportMeterName, AbnormalMetricName).Add(ctx, 1, otelmetric.WithAttributes(attrs...)) } // 耗时 r.getCounter(ServerReportMeterName, CostMetricName).Add(ctx, int64(costMs), otelmetric.WithAttributes(attrs...)) r.getHistogram(ServerReportMeterName, DurationMetricName, DefaultDurationBounds).Record(ctx, costMs, otelmetric.WithAttributes(attrs...)) } ``` ## 10. 自定义 Metric API ### 10.1 概述 提供便捷的 Metric API,简化指标上报操作,支持: - 函数式 API(Context 属性传递) - 函数式 API(显式属性传递) - 面向对象 API(Instrument 封装) - Global/App 双 Provider 支持 ### 10.2 函数式 API(Context 属性) ```go import "github.com/kaydxh/golang/pkg/opentelemetry/metric/api" // 通过 context 传递属性 ctx = api.WithAttribute(ctx, "meter_name", "user_id", "12345") ctx = api.WithAttributes(ctx, "meter_name", map[string]any{ "region": "us-west-2", "version": "1.2.3", }) // Counter api.AddCounter(ctx, "business", "orders_count", 10) api.IncrCounter(ctx, "business", "user_signups") // Histogram api.RecordHistogram(ctx, "latency", "api_duration", 125.5, nil) api.RecordDuration(ctx, "latency", "db_query", 45.2) // 使用默认 bounds ``` ### 10.3 函数式 API(显式属性) ```go import "go.opentelemetry.io/otel/attribute" // 直接传入属性,不依赖 context api.IncrCounterWithAttrs(ctx, "http", "requests", attribute.String("endpoint", "/api/v1/users"), attribute.Int("status", 200), ) api.RecordDurationWithAttrs(ctx, "http", "latency", 45.2, attribute.String("method", "GET"), attribute.String("path", "/users"), ) ``` ### 10.4 面向对象 API ```go // Counter 对象 counter := api.NewCounter("business", "api_calls") counter.SetAttribute("service", "user-service") counter.Incr(ctx) // 链式调用 counter.With("method", "GET").With("path", "/users").Incr(ctx) // Histogram 对象 histogram := api.NewHistogram("latency", "processing_time", api.WithBounds([]float64{10, 50, 100, 500, 1000}), ) histogram.SetAttribute("processor", "image") histogram.Record(ctx, 234.5) // Timer 对象 timer := api.NewTimer("performance", "operation_duration") timer.SetAttribute("operation", "data_processing") timer.Record(ctx, float64(elapsed.Milliseconds())) ``` ### 10.5 Global vs App Provider ```go // App Provider(应用级指标)- 默认 api.IncrCounter(ctx, "business", "orders") counter := api.NewCounter("app", "signups") // Global Provider(基础设施指标) api.GlobalIncrCounter(ctx, "infra", "gc_cycles") globalCounter := api.NewGlobalCounter("system", "allocations") // 设置自定义 App Provider(可选) api.SetAppMeterProvider(myCustomProvider) ``` ### 10.6 配置驱动的双 MeterProvider 支持通过配置文件自动初始化 Global 和 App 两个独立的 MeterProvider: #### Proto 配置定义 ```protobuf message OpenTelemetry { // ... 其他字段 ... // App MeterProvider configuration (separate from global) AppMeterProvider app_meter_provider = 11; } message AppMeterProvider { bool enabled = 1; // Enable separate App MeterProvider // Exporter type for app metrics (if different from global) OtelMetricExporterType exporter_type = 2; // Exporter configuration (if different from global) OtelMetricExporter exporter = 3; // Collect duration for app metrics google.protobuf.Duration collect_duration = 4; // Resource attributes specific to app metrics Resource resource = 5; } ``` #### YAML 配置示例 ```yaml open_telemetry: enabled: true # Global MeterProvider (基础设施指标) otel_metric_exporter_type: metric_prometheus otel_metric_exporter: prometheus: url: "/metrics" metric_collect_duration: "60s" # App MeterProvider (应用级指标,独立配置) app_meter_provider: enabled: true exporter_type: metric_otlp # 可以使用不同的导出器 exporter: otlp: endpoint: "prometheus.tencentcloudapi.com:4317" protocol: "grpc" token: "your-app-token" collect_duration: "30s" # 可以使用不同的采集周期 resource: service_name: "my-app-metrics" attrs: metric_type: "business" ``` #### 使用场景 | 场景 | Global Provider | App Provider | |------|-----------------|--------------| | **用途** | 基础设施/运维指标 | 业务/应用指标 | | **指标类型** | CPU、内存、GC、网络 | 订单数、用户注册、业务延迟 | | **采集周期** | 较长(60s) | 较短(15-30s) | | **导出目标** | 本地 Prometheus | 腾讯云/远程 OTLP | | **资源属性** | 通用服务信息 | 业务相关属性 | #### 编程方式配置 ```go // 方式1:使用配置文件自动初始化 cfg := opentelemetry.NewConfig( opentelemetry.WithViper(v), ) cfg.Complete().New(ctx) // 方式2:编程方式手动配置双 Provider ot := opentelemetry.NewOpenTelemetryService( // Global Provider opentelemetry.WithMeterPullExporter(prometheusBuilder), opentelemetry.WithMetricCollectDuration(time.Minute), // App Provider opentelemetry.WithAppMeterPushExporter(otlpBuilder), opentelemetry.WithAppMetricCollectDuration(30 * time.Second), opentelemetry.WithAppMeterResource(appResource), ) ot.Install(ctx) ``` ### 10.7 支持的属性类型 | 类型 | 示例 | |------|------| | `string` | `"value"` | | `int`, `int8`, `int16`, `int32`, `int64` | `123` | | `uint`, `uint8`, `uint16`, `uint32`, `uint64` | `456` | | `float32`, `float64` | `3.14` | | `bool` | `true` | ### 10.8 默认 Histogram Bounds ```go // 延迟类(毫秒) DefaultDurationBounds = []float64{1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000} // 大小类(字节) DefaultSizeBounds = []float64{100, 1000, 10000, 100000, 1000000, 10000000} ``` ## 11. 资源统计 ### 11.1 ResourceStatsService 自动采集系统资源指标: ```go type ResourceStatsService struct { checkInterval time.Duration // 采集的指标 cpuUsage float64 // CPU 使用率 memoryUsage float64 // 内存使用率 goroutines int // Goroutine 数量 gcPauseNs uint64 // GC 暂停时间 } ``` ### 11.2 采集的指标 | 指标 | 说明 | 类型 | |------|------|------| | `process_cpu_usage` | 进程 CPU 使用率 | Gauge | | `process_memory_usage` | 进程内存使用率 | Gauge | | `go_goroutines` | Goroutine 数量 | Gauge | | `go_gc_duration_seconds` | GC 暂停时间 | Histogram | | `go_memstats_alloc_bytes` | 已分配内存 | Gauge | ## 12. 使用示例 ### 12.1 编程方式配置 ```go import ( "github.com/kaydxh/golang/pkg/opentelemetry" "github.com/kaydxh/golang/pkg/opentelemetry/metric/otlp" ) // 方式一:使用腾讯云 Prometheus 快捷方法 otelService := opentelemetry.NewOpenTelemetryService( opentelemetry.WithMeterOptions( otlp.WithTencentCloudPrometheus( "your-instance.tencentcloudprom.com", "your-token", false, // 使用 TLS ), ), ) otelService.Install(ctx) // 方式二:自定义 OTLP 配置 otelService := opentelemetry.NewOpenTelemetryService( opentelemetry.WithMeterOptions( otlp.WithOTLPPushExporter( "prometheus.example.com:4318", otlp.WithProtocol(otlp.ProtocolHTTP), otlp.WithHeaders(map[string]string{ "Authorization": "Bearer xxx", }), otlp.WithInsecure(true), ), ), ) ``` ### 12.2 配置文件方式 ```yaml # sea-date.yaml web: monitor: open_telemetry: enabled: true metric_collect_duration: 60s otel_metric_exporter_type: metric_otlp otel_metric_exporter: otlp: endpoint: "your-instance.tencentcloudprom.com" token: "your-prometheus-token" protocol: "http" insecure: false ``` ## 13. 文件结构 ``` pkg/opentelemetry/ ├── opentelemetry.go # OpenTelemetryService 主入口 ├── opentelemetry.proto # Proto 配置定义 ├── opentelemetry.pb.go # 生成的 Proto 代码 ├── opentelemetry.yaml # 配置示例 ├── opentelemetry.option.go # OpenTelemetry 选项 ├── config.go # 配置加载和安装 ├── config.option.go # 配置选项 ├── metric/ │ ├── meter.go # MeterProvider 管理 │ ├── meter.option.go # Meter 选项 │ ├── meter.pull.exporter.go # Pull 模式导出器接口 │ ├── meter.push.exporter.go # Push 模式导出器接口 │ ├── api/ # 自定义 Metric API │ │ ├── api.go # 便捷 API 函数 │ │ └── instrument.go # Instrument 对象封装 │ ├── report/ # 模调上报 │ │ ├── report.go # 上报核心实现 │ │ └── dimension.go # 维度定义 │ ├── prometheus/ # Prometheus Pull 导出器 │ │ ├── prometheus.metric.go │ │ └── prometheus.metric_option.go │ ├── otlp/ # OTLP Push 导出器 │ │ ├── otlp.metric.go │ │ ├── otlp.metric.option.go │ │ └── otlp.metric_option.go │ └── stdout/ # Stdout 导出器 │ └── stdout.metric.go ├── tracer/ │ ├── tracer.go # TracerProvider 管理 │ ├── tracer.option.go # Tracer 选项 │ ├── jaeger/ # Jaeger 导出器 │ └── stdout/ # Stdout 导出器 └── resource/ └── resource.go # K8s Resource 属性 pkg/middleware/grpc-middleware/opentelemetry/ ├── metric_server.interceptor.go # gRPC 指标拦截器 ├── trace_server.interceptor.go # gRPC 链路拦截器(Server) ├── trace_client.interceptor.go # gRPC 链路拦截器(Client) ├── modular_server.interceptor.go # 模调上报拦截器(Server/被调) └── modular_client.interceptor.go # 模调上报拦截器(Client/主调) ``` ## 14. 设计特点总结 | 特点 | 说明 | |------|------| | OpenTelemetry 标准 | 基于 CNCF OpenTelemetry 标准实现 | | 多后端支持 | 支持 Prometheus、OTLP、Jaeger、Stdout 等 | | Pull/Push 双模式 | 同时支持 Pull(Prometheus)和 Push(OTLP)模式 | | 腾讯云兼容 | 原生支持腾讯云 Prometheus Remote Write | | APM Token 支持 | 支持腾讯云 APM Token 认证,作为 Resource attribute 注入 | | 智研平台支持 | 支持腾讯内部智研平台,通过 tps.tenant.id 认证,支持 Metric/Trace 上报 | | 配置驱动 | 通过 YAML/Proto 配置灵活切换后端 | | 中间件集成 | gRPC/HTTP 请求自动采集指标和链路 | | 资源监控 | 自动采集 CPU、内存、GC 等系统指标 | | 低侵入性 | 通过中间件透明接入,业务代码无感知 | | K8s 属性 | 自动采集 K8s 容器运行时信息 | | 模调上报 | 支持主调/被调标准化监控 | | 自定义 Metric API | 提供便捷的指标上报 API | | Global/App 双 Provider | 支持基础设施和应用级指标分离 | ## 15. 常见问题排查 ### 15.1 智研上报超时 **现象**: ``` [ERRO] metric export failed: context deadline exceeded: retry-able request failure ``` **原因与解决方案**: | 错误原因 | 解决方案 | |----------|----------| | 使用内网地址但不在内网 | 切换到外网地址 + HTTPS | | 使用外网地址但未启用 TLS | 设置 `insecure: false` | | 网络不通 | 检查防火墙和网络连通性 | **配置对照表**: ```yaml # 内网环境(推荐) endpoint: "<内网metric上报地址>:4318" insecure: true # HTTP # 外网环境 endpoint: "<外网metric上报地址>:4318" insecure: false # 必须 HTTPS ``` ### 15.2 指标未上报到智研 **检查清单**: 1. **必填字段是否配置**: - `__zhiyan_app_mark__`:必须配置 appMark - `__zhiyan_env__`:必须配置环境标识 2. **Temporality 是否正确**: - 智研只支持 `Delta Temporality` - 配置:`temporality_delta: true` 3. **采集周期是否匹配**: - 数据粒度为 60 时,采集周期应为 60s - 配置:`metric_collect_duration: 60s` 4. **压缩是否启用**: - 建议启用 gzip:`compression: true` ### 15.3 指标组/Scope Name 配置 智研模调分析需要正确的指标组: | 指标组 | 用途 | 配置 | |--------|------|------| | `server_report` | 被调上报 | 服务端拦截器 | | `client_report` | 主调上报 | 客户端拦截器 | | `attr_report` | 属性监控 | 自定义业务指标 | | `default` | 默认 | 通用指标 | ```yaml resource: zhiyan: metric_group: "server_report" # 指标组名称 ``` ### 15.4 完整的智研配置示例 ```yaml open_telemetry: enabled: true metric_collect_duration: 60s # 采集周期与数据粒度一致 otel_metric_exporter_type: metric_otlp otel_metric_exporter: otlp: # 根据网络环境选择内网或外网地址 endpoint: "<智研metric上报地址>:4318" protocol: "http" insecure: true # 内网 HTTP / 外网必须 false url_path: "/v1/metrics" compression: true # 启用 gzip 压缩 temporality_delta: true # 必须使用 Delta resource: service_name: "my-service" zhiyan: global_app_mark: "" # 必填:appMark env: "prod" # 必填:环境 instance_mark: "" # 选填:实例标识 expand_key: "no" # 选填:是否扩展属性 metric_group: "server_report" # 选填:指标组 # data_grain: 60 # 选填:数据粒度 (10/30/60) # data_type: "" # 选填:秒级填 "second" ``` ### 15.5 Trace 没有上报日志 **现象**: - Meter 指标正常上报,但 Trace 没有任何 export 日志 - 调用 HTTP 接口后没有看到 span 创建 **原因分析**: | 原因 | 说明 | |------|------| | TracerProvider 初始化时机错误 | otelgrpc interceptor 在创建时会缓存全局 TracerProvider,如果此时 TracerProvider 还没设置,会拿到 noop TracerProvider | | HTTP 请求没有 trace interceptor | gRPC trace interceptor 只对 gRPC 请求生效,HTTP 请求需要单独的 HTTP trace middleware | | Sampler 配置问题 | 默认 Sampler 可能不是 AlwaysSample,导致部分 span 被丢弃 | **解决方案**: 1. **确保 TracerProvider 在 WebServer.Run() 之前初始化**: ```go // options.go 中的正确顺序 s.installLogsOrDie() s.installConfigOrDie() ws, err := s.webServerConfig.Complete().New(ctx) // ← 先创建 WebServer // TracerProvider 可以在 WebServer.New() 之后初始化 // 但必须在 WebServer.Run() 之前完成 s.installOpenTelemetryTracerOrDie(ctx) s.installOpenTelemetryMeterOrDie(ctx, ws) ws.PrepareRun().Run(ctx) // ← 启动前 Provider 已设置好 ``` 2. **HTTP trace middleware 动态获取 TracerProvider**: ```go // HTTP middleware 在每次请求时动态获取 TracerProvider func Trace(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tracer := otel.Tracer(tracerName) // ← 请求时获取,此时已设置好 ctx, span := tracer.Start(ctx, spanName, ...) // ... }) } ``` 3. **gRPC trace interceptor 创建时缓存(注意)**: ```go func UnaryServerTraceInterceptor(opts ...otelgrpc.Option) grpc.UnaryServerInterceptor { // gRPC interceptor 在创建时缓存 TracerProvider tp := otel.GetTracerProvider() defaultOpts := []otelgrpc.Option{ otelgrpc.WithTracerProvider(tp), } defaultOpts = append(defaultOpts, opts...) return otelgrpc.UnaryServerInterceptor(defaultOpts...) } ``` 3. **添加 HTTP trace middleware**: HTTP 请求(如 `GET /Now`)不经过 gRPC interceptor,需要单独添加 HTTP trace middleware: ```go // http trace interceptor func Trace(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // 提取 trace context propagator := otel.GetTextMapPropagator() ctx = propagator.Extract(ctx, propagation.HeaderCarrier(r.Header)) // 创建 span tracer := otel.Tracer("http-trace") spanName := r.Method + " " + r.URL.Path ctx, span := tracer.Start(ctx, spanName, trace.WithSpanKind(trace.SpanKindServer)) defer span.End() r = r.WithContext(ctx) next.ServeHTTP(w, r) }) } ``` 4. **确保使用 AlwaysSample**: ```go tp := sdktrace.NewTracerProvider( sdktrace.WithBatcher(exp, batchOpts...), sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.AlwaysSample()), // 确保所有 span 都被记录 ) ``` **验证日志**: 正确配置后,启动日志应显示: ``` [INFO] TracerProvider created with BatchSpanProcessor (batch_timeout=5s, sampler=AlwaysSample) [INFO] UnaryServerTraceInterceptor: creating trace interceptor, TracerProvider type=*trace.TracerProvider ``` 如果显示 `TracerProvider type=*trace.noopTracerProvider`,说明 TracerProvider 初始化顺序有问题。 ### 15.6 Trace 上报连接失败 (EOF) **现象**: ``` [ERRO] [OTLP] trace export failed: traces export: Post "http://xxx:4318/v1/traces": EOF ``` Span 创建成功,但导出到远程服务器失败。 **原因分析**: | 原因 | 说明 | |------|------| | Endpoint 地址不可达 | 网络不通、DNS 解析失败、防火墙阻断 | | 协议不匹配 | 外网地址需要 HTTPS,但配置了 `insecure: true` | | 端口错误 | gRPC 用 4317,HTTP 用 4318 | **解决方案**: 根据网络环境选择正确的配置: ```yaml # 方案1:内网 gRPC(推荐) otel_trace_exporter: otlp: endpoint: "<内网trace上报地址>:4317" protocol: "grpc" insecure: true # 方案2:内网 HTTP otel_trace_exporter: otlp: endpoint: "<内网trace上报地址>:4318" protocol: "http" insecure: true # 方案3:外网 HTTP(必须 HTTPS) otel_trace_exporter: otlp: endpoint: "<外网trace上报地址>:4318" protocol: "http" insecure: false # 外网必须启用 TLS # 方案4:本地调试(stdout) otel_trace_exporter_type: trace_stdout ``` **智研 Trace 上报地址汇总**: | 网络环境 | 协议 | 地址 | 端口 | TLS | |----------|------|------|------|-----| | 内网 IDC | gRPC | `<内网trace上报地址>` | 4317 | 否 | | 内网 IDC | HTTP | `<内网trace上报地址>` | 4318 | 否 | | 外网/DevCloud | gRPC | `<外网trace上报地址>` | 4317 | 否 | | 外网 | HTTP | `<外网metric上报地址>` | 4318 | **是** | ### 15.7 Tracer 和 Meter 初始化顺序问题 **问题**:Tracer 和 Meter 的初始化顺序有什么要求? **原因分析**: | 组件 | 必须在 WebServer 之前? | 原因 | |------|------------------------|------| | **Tracer** | **否** | HTTP trace middleware 在请求时动态调用 `otel.Tracer()` 获取 TracerProvider | | **Meter** | 否(但有例外) | 指标也是在请求处理时动态调用 `otel.Meter()` 获取 | **HTTP Trace Middleware(动态获取)**: ```go // HTTP trace middleware 在每次请求时动态获取 TracerProvider func Trace(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 请求时动态获取,此时 TracerProvider 已设置 tracer := otel.Tracer(tracerName) // ← 每次请求时获取 ctx, span := tracer.Start(ctx, spanName, ...) defer span.End() next.ServeHTTP(w, r) }) } ``` **gRPC Trace Interceptor(创建时缓存)**: ```go // gRPC interceptor 在创建时获取并缓存 TracerProvider func UnaryServerTraceInterceptor(opts ...otelgrpc.Option) grpc.UnaryServerInterceptor { // 创建时获取全局 TracerProvider 并传入 tp := otel.GetTracerProvider() return otelgrpc.UnaryServerInterceptor(otelgrpc.WithTracerProvider(tp)...) } ``` > **注意**:如果 gRPC interceptor 在 TracerProvider 设置之前创建,会缓存 noop TracerProvider。但当前实现中,HTTP middleware 是动态获取的,所以 Tracer 可以在 WebServer 之后初始化。 **Meter 的例外情况**: 当使用 **Prometheus Pull 模式** 时,需要在 Gin Router 上注册 `/metrics` 端点,此时需要先有 WebServer: ```go // 需要 ws.GetGinEngine() 来注册 /metrics s.opentelemetryConfig.ApplyOptions(opentelemetry_.WithGinRouter(ws.GetGinEngine())) ``` **推荐的初始化顺序**: ``` ┌─────────────────────────────────────────────────────────────┐ │ 启动顺序 │ ├─────────────────────────────────────────────────────────────┤ │ 1. installLogs │ │ 2. installConfig │ │ 3. WebServer.New() │ │ 4. installMysql/Redis │ │ 5. installOpenTelemetryTracer ←── 可以在 WebServer 之后 │ │ 6. installOpenTelemetryMeter ←── 可以在 WebServer 之后 │ │ 7. WebServer.Run() ←── 必须在 Run() 之前完成 │ └─────────────────────────────────────────────────────────────┘ ``` > **关键点**:只要在 `WebServer.Run()` 之前完成 TracerProvider 和 MeterProvider 的初始化即可,因为 HTTP middleware 是在请求时动态获取 Provider 的。 ### 15.8 调试技巧 **1. 启用 stdout exporter 验证 span 创建**: ```yaml otel_trace_exporter_type: trace_stdout # 临时切换到 stdout otel_trace_exporter: stdout: pretty_print: true ``` **2. 启用 metric stdout exporter 查看上报数据**: ```yaml otel_metric_exporter_type: metric_stdout otel_metric_exporter: stdout: pretty_print: true ``` **3. 日志中确认 Resource Attribute**: ``` [DEBU] [OTLP] resource attribute: __zhiyan_app_mark__= ``` **4. 确认 TracerProvider 类型**: ``` [INFO] UnaryServerTraceInterceptor: creating trace interceptor, TracerProvider type=*trace.TracerProvider ``` 如果显示 `*trace.noopTracerProvider`,说明初始化顺序有问题。 **5. 检查 span export 日志**: ``` [DEBU] [OTLP] exporting 1 spans to :4317 [INFO] [OTLP] trace export success: endpoint=xxx, spans=1, duration=xxx ``` **6. 网络连通性测试**: ```bash # 测试 gRPC 端口 nc -zv 4317 # 测试 HTTP 端口 curl -v http://:4318/v1/traces ``` ================================================ FILE: doc/rate_limit_design.md ================================================ # 限流增强功能设计文档 ## 1. 概述 本文档描述了 golang 库中限流(Rate Limit)功能的增强设计,支持**基于 QPS 的限流**、**并发数控制**和**不同接口不同限流策略**的能力。 ## 2. 限流模式分析 ### 2.1 并发控制限流器 (Limiter) 基于**Channel 信号量**的并发控制器: ```go type Limiter struct { mu sync.Mutex burst int // 最大令牌数(最大并发数) sem chan struct{} // 信号量通道 } ``` **特点**: - 控制**同时处理的请求数**(并发数) - 请求完成后需要调用 `Put()` 归还令牌 - 适合控制资源占用,如数据库连接数、goroutine 数量 - 基于 Channel 实现,原生支持超时和 Context 取消 ### 2.2 QPS 限流器 (QPSLimiter) 基于**令牌桶算法**的速率控制器: ```go type QPSLimiter struct { qps float64 // 每秒生成的令牌数 burst int // 桶容量(允许的突发流量) tokens float64 // 当前可用令牌 lastUpdate time.Time // 上次更新时间 } ``` **特点**: - 控制**每秒允许的请求数**(速率) - 令牌按时间自动恢复,无需归还 - 适合流量控制和防止突发流量 ### 2.3 两种模式对比 | 特性 | 并发限流器 (Limiter) | QPS 限流器 (QPSLimiter) | |------|---------------------|------------------------| | 控制目标 | 同时处理的请求数 | 每秒允许的请求数 | | 令牌归还 | 需要 Put() | 不需要(时间自动恢复) | | 适用场景 | 资源保护 | 流量控制 | | 限制维度 | 资源维度 | 时间维度 | | 实现方式 | Channel 信号量 | 令牌桶算法 | | Context 支持 | 原生支持 | 原生支持 | ### 2.4 组合使用 **当 QPS 和并发数同时配置时,两种限流同时生效,取更严格的限制**: ``` 请求进入 ↓ ┌─────────────────────┐ │ QPS限流检查 │ ← 令牌桶算法,按时间恢复 │ (default_qps=1000) │ └─────────┬───────────┘ │ 通过 ↓ ┌─────────────────────┐ │ 并发数检查 │ ← 信号量算法,请求完成归还 │ (max_concurrency=100) │ └─────────┬───────────┘ │ 通过 ↓ 处理请求 ↓ 归还并发令牌 ``` **实际吞吐量 = min(QPS限制, 并发数 × (1000/平均处理时间ms))** ## 3. 架构设计 ### 3.1 整体架构 ``` ┌─────────────────────────────────────────────────────────────────────┐ │ 配置层 (YAML) │ │ ┌───────────────────────────────────────────────────────────────┐ │ │ │ web: │ │ │ │ qps_limit: │ │ │ │ grpc: │ │ │ │ default_qps: 1000 │ │ │ │ max_concurrency: 100 │ │ │ │ http: │ │ │ │ default_qps: 1000 │ │ │ │ max_concurrency: 100 │ │ │ └───────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────┐ │ 中间件层 (Interceptor) │ │ ┌─────────────────────────┐ ┌─────────────────────────────────┐│ │ │ gRPC 拦截器 │ │ HTTP 中间件 ││ │ │ - QPS 限流拦截器 │ │ - QPS 限流中间件 ││ │ │ - 并发控制拦截器 │ │ - 并发控制中间件 ││ │ └─────────────────────────┘ └─────────────────────────────────┘│ └─────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────┐ │ 核心限流器层 │ │ ┌─────────────────────────┐ ┌─────────────────────────────────┐│ │ │ MethodQPSLimiter │ │ MethodLimiter ││ │ │ (方法级 QPS 限流) │ │ (方法级并发控制) ││ │ └─────────────────────────┘ └─────────────────────────────────┘│ │ │ │ │ │ ▼ ▼ │ │ ┌─────────────────────────┐ ┌─────────────────────────────────┐│ │ │ QPSLimiter │ │ Limiter ││ │ │ (令牌桶算法) │ │ (信号量算法) ││ │ └─────────────────────────┘ └─────────────────────────────────┘│ └─────────────────────────────────────────────────────────────────────┘ ``` ### 3.2 方法级限流 支持为不同的 API 接口配置不同的限流策略: ``` ┌─────────────────────────────────────────────────────────────┐ │ MethodQPSLimiter │ │ ┌───────────────────────────────────────────────────────┐ │ │ │ Method -> Limiter Map │ │ │ │ ┌─────────────────────────────────────────────────┐ │ │ │ │ │ /api/v1/users -> QPSLimiter(qps=100, burst=20)│ │ │ │ │ │ /api/v1/orders -> QPSLimiter(qps=50, burst=10)│ │ │ │ │ │ /api/v1/products -> QPSLimiter(qps=200, burst=50)│ │ │ │ │ │ * -> QPSLimiter(qps=10, burst=5) │ │ │ │ │ └─────────────────────────────────────────────────┘ │ │ │ └───────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` ## 4. 配置设计 ### 4.1 配置结构 限流配置统一放在 `web.qps_limit` 下,支持 gRPC 和 HTTP 分别配置: ```yaml web: bind_address: port: 10001 grpc: timeout: 0s http: api_formatter: trivial_api_v20 # QPS限流配置(统一在 web 配置内) qps_limit: # gRPC QPS限流配置 grpc: default_qps: 1000 # 默认QPS,0表示不限制 default_burst: 1500 # 默认突发容量,0表示使用default_qps值 max_concurrency: 100 # 最大并发数限制,0表示不限制 method_qps: # 方法级配置(可选) - method: "/seadate.v1.SeaDateService/Now" qps: 500 burst: 750 max_concurrency: 50 # HTTP QPS限流配置 http: default_qps: 1000 default_burst: 1500 max_concurrency: 100 method_qps: # 路径级配置(可选) - method: "/v1/now" qps: 500 burst: 750 max_concurrency: 50 ``` ### 4.2 配置优先级 ``` 方法级配置 (method_qps) > 全局默认配置 (default_*) ``` | 请求路径 | method_qps 配置 | 实际使用 | |---------|----------------|---------| | `/v1/now` | 有配置 `qps:500` | 使用 500 QPS | | `/v1/users` | 无配置 | 使用 `default_qps: 1000` | ### 4.3 配置参数说明 | 参数 | 类型 | 说明 | 默认值 | |------|------|------|--------| | `default_qps` | float64 | 默认每秒请求数限制,0表示不限制 | 0 | | `default_burst` | int | 默认突发容量,0表示使用default_qps值 | 0 | | `max_concurrency` | int | 最大并发数限制,0表示不限制 | 0 | | `method_qps` | array | 方法级配置列表 | [] | ## 5. 核心实现 ### 5.1 Limiter (并发控制) 基于 **Channel 信号量**实现,移除了对自定义 `sync.Cond` 的依赖: ```go type Limiter struct { mu sync.Mutex burst int // 最大并发数 sem chan struct{} // 信号量通道 } // 创建并发限流器 func NewLimiter(b int) *Limiter // 核心方法 func (lim *Limiter) Allow() bool // 立即获取,不等待 func (lim *Limiter) AllowN(n int) bool // 获取 n 个令牌 func (lim *Limiter) AllowFor(timeout time.Duration) bool // 带超时等待 func (lim *Limiter) AllowContext(ctx context.Context) error // Context 支持 func (lim *Limiter) Put() // 归还令牌 func (lim *Limiter) PutN(n int) // 归还 n 个令牌 // 等待方法 func (lim *Limiter) WaitFor(timeout time.Duration) error func (lim *Limiter) WaitN(timeout time.Duration, n int) error func (lim *Limiter) WaitContext(ctx context.Context) error func (lim *Limiter) WaitNContext(ctx context.Context, n int) error // 查询和动态调整 func (lim *Limiter) Burst() int // 获取最大并发数 func (lim *Limiter) Tokens() int // 获取当前可用令牌 func (lim *Limiter) Bursting() int // 获取当前正在使用的令牌数 func (lim *Limiter) SetBurst(int) // 动态调整最大并发数 ``` **实现原理**: ``` ┌─────────────────────────────────────────────────────────────┐ │ Limiter (Channel 信号量) │ │ ┌───────────────────────────────────────────────────────┐ │ │ │ sem: chan struct{} (buffered channel) │ │ │ │ ┌─────────────────────────────────────────────────┐ │ │ │ │ │ [token] [token] [token] ... [token] │ │ │ │ │ │ ← burst 个预填充令牌 │ │ │ │ │ └─────────────────────────────────────────────────┘ │ │ │ │ │ │ │ │ Allow(): select { case <-sem: return true } │ │ │ │ Put(): select { case sem <- struct{}{}: } │ │ │ └───────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` **相比旧实现的改进**: | 改进点 | 旧实现 | 新实现 | |-------|-------|-------| | 依赖 | 自定义 `sync_.Cond` | 标准库 `channel` | | 超时机制 | `cond.WaitForDo` | `select` + `time.After` | | Context 支持 | 无 | 原生支持 | | 动态调整 | 无 | `SetBurst()` | | 代码复杂度 | 较高 | 简洁 | ### 5.2 QPSLimiter 基于**令牌桶算法**实现: ```go type QPSLimiter struct { mu sync.Mutex qps float64 // 每秒生成的令牌数 burst int // 桶容量(最大令牌数) tokens float64 // 当前可用令牌 lastUpdate time.Time // 上次更新时间 } // 创建 QPS 限流器 func NewQPSLimiter(qps float64, burst int) *QPSLimiter // 核心方法 func (l *QPSLimiter) Allow() bool // 立即判断是否允许 func (l *QPSLimiter) AllowN(n int) bool // 请求 n 个令牌 func (l *QPSLimiter) Wait(ctx context.Context) error // 阻塞等待令牌 func (l *QPSLimiter) AllowFor(timeout time.Duration) bool // 带超时等待 ``` ### 5.3 MethodQPSLimiter ```go type MethodQPSLimiter struct { mu sync.RWMutex limiters map[string]*QPSLimiter // 方法 -> 限流器映射 global *QPSLimiter // 默认全局限流器 } // 方法 QPS 配置 type MethodQPSConfig struct { Method string // API 方法名 QPS float64 // 每秒请求数 Burst int // 突发容量 } // 创建方法级限流器 func NewMethodQPSLimiter(defaultQPS float64, defaultBurst int) *MethodQPSLimiter func NewMethodQPSLimiterWithConfigs(defaultQPS float64, defaultBurst int, configs []MethodQPSConfig) (*MethodQPSLimiter, error) // 动态管理方法限流 func (m *MethodQPSLimiter) AddMethod(method string, qps float64, burst int) error func (m *MethodQPSLimiter) SetMethodQPS(method string, qps float64, burst int) error func (m *MethodQPSLimiter) RemoveMethod(method string) // 限流判断(自动选择对应的限流器) func (m *MethodQPSLimiter) Allow(method string) bool func (m *MethodQPSLimiter) AllowFor(method string, timeout time.Duration) bool ``` ### 5.4 配置转换 ```go // QPSLimitConfig 限流配置结构 type QPSLimitConfig struct { DefaultQPS float64 DefaultBurst int MaxConcurrency int MethodQPS []MethodQPSConfigItem } // 转换为gRPC网关QPS限流配置 func (c *QPSLimitConfig) ToGRPCQPSLimitConfig() gw_.QPSLimitConfig // 转换为HTTP QPS限流配置 func (c *QPSLimitConfig) ToHTTPQPSLimitConfig() gw_.HTTPQPSLimitConfig ``` ## 6. 中间件集成 ### 6.1 gRPC 拦截器 ```go // 创建方法级 QPS 限流器 limiter := ratelimit.NewMethodQPSLimiter(100, 20) // 默认 100 QPS limiter.AddMethod("/service.UserService/GetUser", 500, 100) limiter.AddMethod("/service.OrderService/CreateOrder", 50, 10) // 应用拦截器 server := grpc.NewServer( grpc.UnaryInterceptor(ratelimit.UnaryServerInterceptorQPS(limiter)), grpc.StreamInterceptor(ratelimit.StreamServerInterceptorQPS(limiter)), ) ``` ### 6.2 HTTP 中间件 ```go // 创建 QPS 限流器 limiter := ratelimit.NewQPSRateLimiter(100, 20) // 默认 100 QPS limiter.AddPath("/api/v1/users", 500, 100) limiter.AddPath("/api/v1/orders", 50, 10) // 应用中间件 http.Handle("/", limiter.Handler(yourHandler)) // 暴露限流统计 http.Handle("/debug/ratelimit", limiter.StatsHandler()) ``` ### 6.3 通过配置自动集成 在 `webserver.Config` 中自动安装限流中间件: ```go // installHttpMiddlewareChain 安装 HTTP 中间件链 func (c *Config) installHttpMiddlewareChain() []gw_.GRPCGatewayOption { // ... 其他中间件 // QPS限流和并发控制(通过扩展配置) if c.opts.httpQPSLimit != nil { opts = append(opts, gw_.WithHttpHandlerInterceptorsQPSLimitOptions( c.opts.httpQPSLimit.ToHTTPQPSLimitConfig(), )) } return opts } // installGrpcMiddlewareChain 安装 gRPC 中间件链 func (c *Config) installGrpcMiddlewareChain() []gw_.GRPCGatewayOption { // ... 其他中间件 // QPS限流和并发控制(通过扩展配置) if c.opts.grpcQPSLimit != nil { opts = append(opts, gw_.WithServerInterceptorsQPSLimitOptions( c.opts.grpcQPSLimit.ToGRPCQPSLimitConfig(), )) } return opts } ``` ## 7. 使用示例 ### 7.1 并发限流器基本使用 ```go // 创建并发限流器:最大 100 并发 limiter := rate.NewLimiter(100) // 立即获取令牌 if limiter.Allow() { defer limiter.Put() // 处理请求 } // 带超时等待 if limiter.AllowFor(100 * time.Millisecond) { defer limiter.Put() // 处理请求 } // 使用 Context(推荐) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if err := limiter.AllowContext(ctx); err == nil { defer limiter.Put() // 处理请求 } // 动态调整最大并发数 limiter.SetBurst(200) ``` ### 7.2 QPS 限流器基本使用 ```go // 创建 QPS 限流器:100 QPS,允许突发 20 个请求 limiter := rate.NewQPSLimiter(100, 20) // 判断是否允许 if limiter.Allow() { // 处理请求 } // 带超时等待 if limiter.AllowFor(100 * time.Millisecond) { // 处理请求 } // 阻塞等待 ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if err := limiter.Wait(ctx); err == nil { // 处理请求 } ``` ### 7.3 方法级限流 ```go // 配置不同接口的 QPS configs := []rate.MethodQPSConfig{ {Method: "/api/v1/users", QPS: 100, Burst: 20}, {Method: "/api/v1/orders", QPS: 50, Burst: 10}, {Method: "/api/v1/products", QPS: 200, Burst: 50}, } // 创建限流器,默认 10 QPS limiter, _ := rate.NewMethodQPSLimiterWithConfigs(10, 5, configs) // 使用(自动选择对应的限流器) limiter.Allow("/api/v1/users") // 使用 100 QPS limiter.Allow("/api/v1/orders") // 使用 50 QPS limiter.Allow("/api/v1/unknown") // 使用默认 10 QPS ``` ### 7.4 动态调整 ```go limiter := rate.NewMethodQPSLimiter(100, 20) // 动态添加方法限流 limiter.AddMethod("/api/v1/hot-endpoint", 500, 100) // 动态调整 QPS limiter.SetMethodQPS("/api/v1/hot-endpoint", 1000, 200) // 移除方法限流(使用全局限流) limiter.RemoveMethod("/api/v1/hot-endpoint") // 调整全局 QPS limiter.SetGlobalQPS(200, 50) ``` ### 7.5 查看统计 ```go limiter := rate.NewMethodQPSLimiter(100, 20) limiter.AddMethod("/api/v1/users", 500, 100) // 获取统计信息 stats := limiter.Stats() for _, s := range stats { fmt.Printf("Method: %s, QPS: %.0f, Burst: %d, Available: %.1f\n", s.Method, s.QPS, s.Burst, s.Tokens) } // Output: // Method: *, QPS: 100, Burst: 20, Available: 20.0 // Method: /api/v1/users, QPS: 500, Burst: 100, Available: 100.0 ``` ### 7.6 压测验证 ```bash # 配置 max_concurrency: 10 后进行压测 bombardier -n 30000 -c 3000 -t 10s -H Content-type:application/json -m POST http://127.0.0.1:10001/Now # 预期结果:大量请求被限流拒绝,返回 429 # HTTP codes: # 1xx - 0, 2xx - 2047, 3xx - 0, 4xx - 27869, 5xx - 0 # 4xx 表示被限流拒绝的请求(HTTP 429 Too Many Requests) ``` ## 8. API 响应格式 ### 8.1 HTTP 限流响应 **QPS 限流**: ```json HTTP/1.1 429 Too Many Requests Content-Type: application/json Retry-After: 1 { "error": "rate_limit_exceeded", "message": "GET /api/v1/users is rejected by http_qps middleware, QPS limit exceeded", "code": 429 } ``` **并发数限流**: ```json HTTP/1.1 429 Too Many Requests Content-Type: application/json { "error": "concurrency_limit_exceeded", "message": "POST /Now is rejected by http_concurrency middleware, max concurrency exceeded", "code": 429 } ``` ### 8.2 gRPC 限流响应 ``` code: RESOURCE_EXHAUSTED message: "/service.UserService/GetUser is rejected, QPS limit exceeded" ``` ## 9. 文件结构 ``` go/time/rate/ ├── rate.go # 并发控制限流器(信号量) ├── rate_method.go # 方法级并发限流器 ├── rate_qps.go # QPS 限流器(令牌桶) ├── rate_qps_method.go # 方法级 QPS 限流器 ├── rate_qps_test.go # QPS 限流器测试 └── rate_test.go # 并发限流器测试 pkg/webserver/ ├── config.go # Web 服务配置(安装限流中间件) ├── config.option.go # 配置选项 ├── webserver.proto # Proto 定义 ├── webserver.yaml # 示例配置 └── webserver_qps_limit.go # QPS 限流配置转换 pkg/grpc-gateway/ ├── grpc_gateway_grpc.option.go # gRPC QPS 限流选项 └── grpc_gateway_http.option.go # HTTP QPS 限流选项 pkg/middleware/grpc-middleware/ratelimit/ ├── ratelimit_server.interceptor.go # 并发限流拦截器 └── ratelimit_qps_server.interceptor.go # QPS 限流拦截器 pkg/middleware/http-middleware/ratelimiter/ ├── ratelimiter.go # 并发限流中间件 └── ratelimiter_qps.go # QPS 限流中间件 ``` ## 10. 设计特点总结 | 特点 | 说明 | |------|------| | 双重限流 | 同时支持 QPS 限流(令牌桶)和并发控制(Channel 信号量) | | 配置统一 | 限流配置统一放在 `web.qps_limit` 下,结构清晰 | | 方法级配置 | 支持为不同 API 接口配置不同的限流策略 | | 动态调整 | 运行时动态添加、修改、删除方法限流配置,支持 `SetBurst()` | | 等待模式 | 支持立即返回、带超时等待、阻塞等待三种模式 | | Context 支持 | 原生支持 `context.Context`,符合 Go 惯例 | | 统计信息 | 提供限流统计接口,便于监控和调试 | | 线程安全 | 使用 Channel 和互斥锁保证并发安全 | | 无外部依赖 | 仅依赖标准库,移除了对自定义 `sync.Cond` 的依赖 | | 向后兼容 | 旧的 `max_concurrency_unary` 等配置已废弃,统一使用新配置 | ## 11. 废弃配置说明 以下配置已废弃,统一使用 `web.qps_limit` 配置: | 废弃配置 | 新配置 | |---------|-------| | `web.grpc.max_concurrency_unary` | `web.qps_limit.grpc.max_concurrency` | | `web.grpc.max_concurrency_stream` | `web.qps_limit.grpc.max_concurrency` | | `web.http.max_concurrency` | `web.qps_limit.http.max_concurrency` | ## 12. 实现演进 ### 12.1 Limiter 重构(v2.0) **变更原因**: - 旧实现依赖自定义 `sync_.Cond`,增加了维护成本 - 自定义 Cond 的超时实现复杂,不如 Channel 原生支持 **变更内容**: | 项目 | 旧实现 | 新实现 | |------|-------|-------| | 核心数据结构 | `tokens int` + `sync_.Cond` | `sem chan struct{}` | | 超时等待 | `cond.WaitForDo(timeout, pred, do)` | `select { case <-sem: case <-time.After(timeout): }` | | Context 支持 | 无 | `AllowContext()`, `WaitContext()` | | 动态调整 | 无 | `SetBurst()` | | 依赖 | `github.com/kaydxh/golang/go/sync` | 仅标准库 | **API 兼容性**: - ✅ `Allow()`, `AllowFor()`, `AllowWaitUntil()` - 签名不变 - ✅ `Put()`, `PutN()` - 签名不变 - ✅ `WaitFor()`, `WaitN()` - 签名不变 - ✅ `Burst()`, `Bursting()` - 签名不变 - ➕ 新增 `Tokens()`, `SetBurst()`, `AllowN()`, `AllowContext()`, `WaitContext()`, `WaitNContext()` ================================================ FILE: doc.go ================================================ package golang import _ "github.com/kaydxh/golang/go" ================================================ FILE: go/archive/archive.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 archive import ( "github.com/kaydxh/golang/go/archive/option" ) // Archiver defines the interface for archive extraction operations type Archiver interface { // Extract extracts all files from srcFile to destDir and returns a list of extracted file info Extract(srcFile, destDir string) ([]*option.FileInfo, error) // ExtractStream extracts files from srcFile to destDir and streams the results through a channel ExtractStream(srcFile, destDir string) <-chan option.ExtractMsg } ================================================ FILE: go/archive/option/file_info.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 option import ( "fmt" "os" ) type FileInfo struct { Path string FileInfo os.FileInfo } func (e *FileInfo) String() string { return fmt.Sprintf( "{path: [%v], size: [%v], modeTime: [%v]}", e.Path, e.FileInfo.Size(), e.FileInfo.ModTime(), ) } type ExtractMsg struct { FileInfo *FileInfo Error error } func (e *ExtractMsg) String() string { if e.Error != nil { return fmt.Sprintf("{error: %v}", e.Error) } if e.FileInfo == nil { return "{fileInfo: nil}" } return fmt.Sprintf( "{path: [%v], size: [%v], modeTime: [%v]}", e.FileInfo.Path, e.FileInfo.FileInfo.Size(), e.FileInfo.FileInfo.ModTime(), ) } ================================================ FILE: go/archive/zip/zip.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 zip import ( "archive/zip" "bytes" "fmt" "io" "path/filepath" "strings" "unicode/utf8" "github.com/kaydxh/golang/go/archive/option" os_ "github.com/kaydxh/golang/go/os" "golang.org/x/text/encoding/simplifiedchinese" "golang.org/x/text/transform" ) // Zip implements the Archiver interface for ZIP archive extraction type Zip struct { } func (z Zip) Extract(srcFile, destDir string) ([]*option.FileInfo, error) { r, err := zip.OpenReader(srcFile) if err != nil { return nil, fmt.Errorf("failed to open zip file %s: %w", srcFile, err) } defer r.Close() err = os_.MakeDirAll(destDir) if err != nil { return nil, fmt.Errorf("failed to create destination directory %s: %w", destDir, err) } var extractedFiles []*option.FileInfo for _, f := range r.File { fileInfo, err := z.extractAndWriteFile(destDir, f) if err != nil { return nil, fmt.Errorf("failed to extract file %s: %w", f.Name, err) } if fileInfo != nil { extractedFiles = append(extractedFiles, fileInfo) } } return extractedFiles, nil } func (z Zip) ExtractStream( srcFile, destDir string, ) <-chan option.ExtractMsg { fileInfoCh := make(chan option.ExtractMsg, 1024) go func() { defer close(fileInfoCh) r, err := zip.OpenReader(srcFile) if err != nil { fileInfoCh <- option.ExtractMsg{ Error: fmt.Errorf("failed to open zip file %s: %w", srcFile, err), } return } defer r.Close() err = os_.MakeDirAll(destDir) if err != nil { fileInfoCh <- option.ExtractMsg{ Error: fmt.Errorf("failed to create destination directory %s: %w", destDir, err), } return } for _, f := range r.File { fileInfo, err := z.extractAndWriteFile(destDir, f) if err != nil { fileInfoCh <- option.ExtractMsg{ Error: fmt.Errorf("failed to extract file %s: %w", f.Name, err), } // Continue processing other files instead of returning continue } if fileInfo != nil { fileInfoCh <- option.ExtractMsg{ FileInfo: fileInfo, Error: nil, } } } }() return fileInfoCh } func (z Zip) extractAndWriteFile( destDir string, f *zip.File, ) (*option.FileInfo, error) { if f == nil { return nil, fmt.Errorf("invalid zip file") } decodeName := f.Name if !utf8.Valid([]byte(f.Name)) { i := bytes.NewReader([]byte(f.Name)) decoder := transform.NewReader( i, simplifiedchinese.GB18030.NewDecoder(), ) content, err := io.ReadAll(decoder) if err != nil { return nil, fmt.Errorf("failed to decode filename %s: %w", f.Name, err) } decodeName = string(content) } baseName := filepath.Base(f.Name) if strings.HasPrefix(baseName, ".") { return nil, nil } rc, err := f.Open() if err != nil { return nil, fmt.Errorf("failed to open file %s from zip: %w", f.Name, err) } defer func() { if closeErr := rc.Close(); closeErr != nil { // If there's already an error, wrap it; otherwise set the close error if err != nil { err = fmt.Errorf("%w; close error: %v", err, closeErr) } else { err = fmt.Errorf("failed to close file %s: %w", f.Name, closeErr) } } }() // Security check: prevent zip slip attack by ensuring the resolved path is within destDir path := filepath.Join(destDir, decodeName) resolvedPath, err := filepath.Abs(path) if err != nil { return nil, fmt.Errorf("failed to resolve path %s: %w", path, err) } destDirAbs, err := filepath.Abs(destDir) if err != nil { return nil, fmt.Errorf("failed to resolve destination directory %s: %w", destDir, err) } if !strings.HasPrefix(resolvedPath, destDirAbs+string(filepath.Separator)) && resolvedPath != destDirAbs { return nil, fmt.Errorf("zip slip detected: file path %s is outside destination directory %s", decodeName, destDir) } if f.FileInfo().IsDir() { err = os_.MakeDirAll(resolvedPath) if err != nil { return nil, fmt.Errorf("failed to create directory %s: %w", resolvedPath, err) } return nil, nil } fn, err := os_.OpenFile(resolvedPath, false) if err != nil { return nil, fmt.Errorf("failed to create file %s: %w", resolvedPath, err) } defer fn.Close() _, err = io.Copy(fn, rc) if err != nil { return nil, fmt.Errorf("failed to write file %s: %w", resolvedPath, err) } return &option.FileInfo{ Path: fn.Name(), FileInfo: f.FileInfo(), }, nil } ================================================ FILE: go/archive/zip/zip_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 zip_test import ( "testing" zip_ "github.com/kaydxh/golang/go/archive/zip" ) func TestExtractZip(t *testing.T) { srcFile := "./新词词典.zip" destDir := "unzip" fileInfos, err := zip_.Zip{}.Extract(srcFile, destDir) if err != nil { t.Errorf("failed to Extract zip file: [%v], err: [%v]", srcFile, err) } t.Logf("extract file: [%v], result: [%+v]", srcFile, fileInfos) /* for extractMsg := range zip_.Zip{}.Extract(srcFile, destDir) { if extractMsg.Err != nil { fmt.Println(msg.Error) } else { fmt.Printf("fileInfo:[%v]", *msg.FileInfo) } } */ } ================================================ FILE: go/bytes/bytes.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 bytes import ( "reflect" "unsafe" ) func Truncate(s []byte, n int) []byte { if n < 0 { n = 0 } if len(s) <= n { return s } return s[:n] } func Encode[T any](m T) []byte { if reflect.ValueOf(m).IsZero() { return nil } sz := int(unsafe.Sizeof(m)) p := make([]byte, sz) slice := (*reflect.SliceHeader)(unsafe.Pointer(&p)) slice.Data = uintptr(unsafe.Pointer(&m)) slice.Len = sz slice.Cap = sz return p } func Decode[T any](b []byte) T { var zero T if len(b) == 0 { return zero } var m T = *(*T)(unsafe.Pointer(&b[0])) return m } ================================================ FILE: go/bytes/bytes_test.go ================================================ package bytes_test import ( "fmt" "testing" "unsafe" bytes_ "github.com/kaydxh/golang/go/bytes" ) func TestEncodeAndDecode(t *testing.T) { // to bytes type MyStruct struct { X, Y, Z int Name string } testCases := []struct { s MyStruct expected string }{ { s: MyStruct{1, 20, 30, "foobar"}, expected: "", }, } const sz = int(unsafe.Sizeof(MyStruct{})) fmt.Printf("MyStruct size: %v\n", int(unsafe.Sizeof(MyStruct{}))) for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { b := bytes_.Encode(testCase.s) fmt.Println(b) fmt.Printf("size of b: %v\n", len(b)) /* var p []byte = (*(*[sz]byte)(unsafe.Pointer(&testCase.s)))[:] fmt.Println(p) fmt.Printf("size of p: %v\n", len(p)) */ /* var m = *(*MyStruct)(unsafe.Pointer(&b[0])) fmt.Println(m) */ r := bytes_.Decode[MyStruct](b) fmt.Println(r) }) } } ================================================ FILE: go/client/client.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 client import ( "log" ) type Client struct { // options opts struct { Path string ErrorLog *log.Logger } } func New(options ...ClientOption) *Client { c := &Client{} c.ApplyOptions(options...) return c } func (c *Client) logf(format string, args ...interface{}) { if c.opts.ErrorLog != nil { c.opts.ErrorLog.Printf(format, args...) } else { log.Printf(format, args...) } } ================================================ FILE: go/client/client.options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 client func WithClientOptionPath(path string) ClientOption { return ClientOptionFunc(func(opt *Client) { opt.opts.Path = path }) } ================================================ FILE: go/client/client_options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 client // A ClientOption sets options. type ClientOption interface { apply(*Client) } // EmptyClientUrlOption does not alter the Clienturation. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyClientOption struct{} func (EmptyClientOption) apply(*Client) {} // ClientOptionFunc wraps a function that modifies Client into an // implementation of the ClientOption interface. type ClientOptionFunc func(*Client) func (f ClientOptionFunc) apply(do *Client) { f(do) } // sample code for option, default for nothing to change func _ClientOptionWithDefault() ClientOption { return ClientOptionFunc(func(*Client) { // nothing to change }) } func (o *Client) ApplyOptions(options ...ClientOption) *Client { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/client/client_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 client_test import ( "fmt" "testing" "github.com/kaydxh/golang/go/client" ) func TestNew(t *testing.T) { conf := client.New(client.WithClientOptionPath("/data/conf")) fmt.Println(conf) } ================================================ FILE: go/container/heap/heap.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 heap import ( "container/heap" "fmt" "sync" ) const ( closedMsg = "heap is closed" ) // LessFunc is used to compare two objects in the heap. type LessFunc func(interface{}, interface{}) bool // KeyFunc knows how to make a key from an object. Implementations // should be deterministic. type KeyFunc func(interface{}) string type heapItem struct { obj interface{} // The object which is stored in the heap. index int // The index of the object's key in the Heap.queue. } type itemKeyValue struct { key string obj interface{} } // heapData is an internal struct that implements the standard heap interface // and keeps the data stored in the heap. type heapData struct { // items is a map from key of the objects to the objects and their index. // We depend on the property that items in the map are in the queue and vice versa. items map[string]*heapItem // queue implements a heap data structure and keeps the order of elements // according to the heap invariant. The queue keeps the keys of objects stored // in "items". queue []string // keyFunc is used to make the key used for queued item insertion and retrieval, and // should be deterministic. keyFunc KeyFunc // lessFunc is used to compare two objects in the heap. lessFunc LessFunc } var ( _ = heap.Interface(&heapData{}) // heapData is a standard heap ) // Less compares two objects and returns true if the first one should go // in front of the second one in the heap. func (h *heapData) Less(i, j int) bool { if i > len(h.queue) || j > len(h.queue) { return false } itemi, ok := h.items[h.queue[i]] if !ok { return false } itemj, ok := h.items[h.queue[j]] if !ok { return false } return h.lessFunc(itemi.obj, itemj.obj) } // Len returns the number of items in the Heap. func (h *heapData) Len() int { return len(h.queue) } // Swap implements swapping of two elements in the heap. This is a part of standard // heap interface and should never be called directly. func (h *heapData) Swap(i, j int) { h.queue[i], h.queue[j] = h.queue[j], h.queue[i] item := h.items[h.queue[i]] item.index = i item = h.items[h.queue[j]] item.index = j } // Push is supposed to be called by heap.Push only. func (h *heapData) Push(kv interface{}) { keyValue := kv.(*itemKeyValue) n := len(h.queue) h.items[keyValue.key] = &heapItem{keyValue.obj, n} h.queue = append(h.queue, keyValue.key) } // Pop is supposed to be called by heap.Pop only. func (h *heapData) Pop() interface{} { key := h.queue[len(h.queue)-1] h.queue = h.queue[0 : len(h.queue)-1] item, ok := h.items[key] if !ok { // This is an error return nil } delete(h.items, key) return item.obj } // Heap is a thread-safe producer/consumer queue that implements a heap data structure. // It can be used to implement priority queues and similar data structures. type Heap struct { lock sync.RWMutex cond sync.Cond // data stores objects and has a queue that keeps their ordering according // to the heap invariant. data *heapData // closed indicates that the queue is closed. // It is mainly used to let Pop() exit its control loop while waiting for an item. closed bool } // Close the Heap and signals condition variables that may be waiting to pop // items from the heap. func (h *Heap) Close() { h.lock.Lock() defer h.lock.Unlock() h.closed = true h.cond.Broadcast() } // Add inserts an item, and puts it in the queue. The item is updated if it // already exists. func (h *Heap) Add(obj interface{}) error { key := h.data.keyFunc(obj) h.lock.Lock() defer h.lock.Unlock() if h.closed { return fmt.Errorf(closedMsg) } if _, exists := h.data.items[key]; exists { h.data.items[key].obj = obj heap.Fix(h.data, h.data.items[key].index) } else { h.addIfNotPresentLocked(key, obj) } h.cond.Broadcast() return nil } // BulkAdd adds all the items in the list to the queue and then signals the condition // variable. It is useful when the caller would like to add all of the items // to the queue before consumer starts processing them. func (h *Heap) BulkAdd(list []interface{}) error { h.lock.Lock() defer h.lock.Unlock() if h.closed { return fmt.Errorf(closedMsg) } for _, obj := range list { key := h.data.keyFunc(obj) if _, exists := h.data.items[key]; exists { h.data.items[key].obj = obj heap.Fix(h.data, h.data.items[key].index) } else { h.addIfNotPresentLocked(key, obj) } } h.cond.Broadcast() return nil } // AddIfNotPresent inserts an item, and puts it in the queue. If an item with // the key is present in the map, no changes is made to the item. // // This is useful in a single producer/consumer scenario so that the consumer can // safely retry items without contending with the producer and potentially enqueueing // stale items. func (h *Heap) AddIfNotPresent(obj interface{}) error { id := h.data.keyFunc(obj) h.lock.Lock() defer h.lock.Unlock() if h.closed { return fmt.Errorf(closedMsg) } h.addIfNotPresentLocked(id, obj) h.cond.Broadcast() return nil } // AddIfHeapOrder inserts an item, and puts it in the queue. If an item with // the key is present in the map, and new obj meet the sort of heap, // then update the item, or no changes is made to the item. func (h *Heap) AddIfHeapOrder(obj interface{}) error { key := h.data.keyFunc(obj) h.lock.Lock() defer h.lock.Unlock() if h.closed { return fmt.Errorf(closedMsg) } if existedObj, exists := h.data.items[key]; exists { if !h.data.lessFunc(existedObj.obj, obj) { h.data.items[key].obj = obj heap.Fix(h.data, h.data.items[key].index) } } else { h.addIfNotPresentLocked(key, obj) } h.cond.Broadcast() return nil } // addIfNotPresentLocked assumes the lock is already held and adds the provided // item to the queue if it does not already exist. func (h *Heap) addIfNotPresentLocked(key string, obj interface{}) { if _, exists := h.data.items[key]; exists { return } heap.Push(h.data, &itemKeyValue{key, obj}) } // Update is the same as Add in this implementation. When the item does not // exist, it is added. func (h *Heap) Update(obj interface{}) error { return h.Add(obj) } // Delete removes an item. func (h *Heap) Delete(obj interface{}) error { key := h.data.keyFunc(obj) h.lock.Lock() defer h.lock.Unlock() if item, ok := h.data.items[key]; ok { heap.Remove(h.data, item.index) return nil } return fmt.Errorf("object not found") } // Pop waits until an item is ready. If multiple items are // ready, they are returned in the order given by Heap.data.lessFunc. func (h *Heap) Pop() (interface{}, error) { h.lock.Lock() defer h.lock.Unlock() for len(h.data.queue) == 0 { // When the queue is empty, invocation of Pop() is blocked until new item is enqueued. // When Close() is called, the h.closed is set and the condition is broadcast, // which causes this loop to continue and return from the Pop(). if h.closed { return nil, fmt.Errorf("heap is closed") } h.cond.Wait() } obj := heap.Pop(h.data) if obj == nil { return nil, fmt.Errorf("object was removed from heap data") } return obj, nil } // List returns a list of all the items. func (h *Heap) List() []interface{} { h.lock.RLock() defer h.lock.RUnlock() list := make([]interface{}, 0, len(h.data.items)) for _, item := range h.data.items { list = append(list, item.obj) } return list } // ListKeys returns a list of all the keys of the objects currently in the Heap. // Note: the key order is random, because it's data structure is map func (h *Heap) ListKeys() []string { h.lock.RLock() defer h.lock.RUnlock() list := make([]string, 0, len(h.data.items)) for key := range h.data.items { list = append(list, key) } return list } // Get returns the requested item, or sets exists=false. // return item.obj, exists func (h *Heap) Get(obj interface{}) (interface{}, bool) { key := h.data.keyFunc(obj) return h.GetByKey(key) } // GetByKey returns the requested item, or sets exists=false. func (h *Heap) GetByKey(key string) (interface{}, bool) { h.lock.RLock() defer h.lock.RUnlock() item, exists := h.data.items[key] if !exists { return nil, false } return item.obj, true } // IsClosed returns true if the queue is closed. func (h *Heap) IsClosed() bool { h.lock.RLock() defer h.lock.RUnlock() if h.closed { return true } return false } // NewHeap returns a Heap which can be used to queue up items to process. func NewHeap(keyFn KeyFunc, lessFn LessFunc) *Heap { h := &Heap{ data: &heapData{ items: map[string]*heapItem{}, queue: []string{}, keyFunc: keyFn, lessFunc: lessFn, }, } h.cond.L = &h.lock return h } ================================================ FILE: go/container/heap/heap_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 heap_test import ( "sync" "testing" heap_ "github.com/kaydxh/golang/go/container/heap" ) func testHeapObjectKeyFunc(obj interface{}) string { return obj.(testHeapObject).name } type testHeapObject struct { name string val interface{} } func mkHeapObj(name string, val interface{}) testHeapObject { return testHeapObject{name: name, val: val} } //minheap func compareInts(val1 interface{}, val2 interface{}) bool { first := val1.(testHeapObject).val.(int) second := val2.(testHeapObject).val.(int) return first < second } // TestHeapBasic tests Heap invariant and synchronization. func TestHeapBasic(t *testing.T) { h := heap_.NewHeap(testHeapObjectKeyFunc, compareInts) var wg sync.WaitGroup wg.Add(2) const amount = 10 var i, u int // Insert items in the heap in opposite orders in two go routines. go func() { for i = amount; i > 0; i-- { h.Add(mkHeapObj(string([]rune{'a', rune(i)}), i)) } wg.Done() }() go func() { for u = 0; u < amount; u++ { h.Add(mkHeapObj(string([]rune{'b', rune(u)}), u+1)) } wg.Done() }() // Wait for the two go routines to finish. wg.Wait() t.Logf("heap: %+v", h.List()) // Make sure that the numbers are popped in ascending order. prevNum := 0 for i := 0; i < amount*2; i++ { obj, err := h.Pop() num := obj.(testHeapObject).val.(int) // All the items must be sorted. if err != nil || prevNum > num { t.Errorf("got %v out of order, last was %v", obj, prevNum) } t.Logf("get %v", num) prevNum = num } } // TestHeap_Get tests Heap.Get. func TestHeap_Get(t *testing.T) { h := heap_.NewHeap(testHeapObjectKeyFunc, compareInts) h.Add(mkHeapObj("foo", 10)) h.Add(mkHeapObj("bar", 1)) h.Add(mkHeapObj("bal", 31)) h.Add(mkHeapObj("baz", 11)) // Get works with the key. obj, exists := h.Get(mkHeapObj("baz", 0)) if !exists || obj.(testHeapObject).val != 11 { t.Fatalf("unexpected error in getting element") } // Get non-existing object. _, exists = h.Get(mkHeapObj("non-existing", 0)) if exists { t.Fatalf("didn't expect to get any object") } } // TestHeap_GetByKey tests Heap.GetByKey and is very similar to TestHeap_Get. func TestHeap_GetByKey(t *testing.T) { h := heap_.NewHeap(testHeapObjectKeyFunc, compareInts) h.Add(mkHeapObj("foo", 10)) h.Add(mkHeapObj("bar", 1)) h.Add(mkHeapObj("bal", 31)) h.Add(mkHeapObj("baz", 11)) obj, exists := h.GetByKey("baz") if exists == false || obj.(testHeapObject).val != 11 { t.Fatalf("unexpected error in getting element") } // Get non-existing object. _, exists = h.GetByKey("non-existing") if exists { t.Fatalf("didn't expect to get any object") } } type Student struct { Id string Name string Score float32 } func testStudentObjectKeyFunc(obj interface{}) string { return obj.(*Student).Id } //maxheap func compareStudentScore(val1 interface{}, val2 interface{}) bool { first := val1.(*Student).Score second := val2.(*Student).Score return first > second } func TestMaxHeap(t *testing.T) { h := heap_.NewHeap(testStudentObjectKeyFunc, compareStudentScore) h.AddIfHeapOrder(&Student{ Id: "id_1", Name: "name_1", Score: 89.2, }) h.AddIfHeapOrder(&Student{ Id: "id_2", Name: "name_2", Score: 87.2, }) h.AddIfHeapOrder(&Student{ Id: "id_3", Name: "name_3", Score: 97.2, }) h.AddIfHeapOrder(&Student{ Id: "id_1", Name: "name_3", Score: 88.2, }) t.Logf("list key: %v", h.ListKeys()) sz := len(h.ListKeys()) for i := 0; i < sz; i++ { obj, err := h.Pop() if err != nil { t.Fatalf("failed to pop, err: %v", err) } t.Logf("get obj: %v", obj.(*Student)) } } ================================================ FILE: go/container/set/set.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 set import ( "encoding/json" "sort" ) // type Set[type T comparable] map[T]Empty type Set[T comparable] map[T]Empty func New[T comparable](items ...T) Set[T] { // func New[T comparable]() Set[T] { ss := make(Set[T], len(items)) ss.Insert(items...) return ss } // Insert adds items to the set. func (s Set[T]) Insert(items ...T) Set[T] { for _, item := range items { s[item] = Empty{} } return s } // Delete removes all items from the set. func (s Set[T]) Delete(items ...T) Set[T] { for _, item := range items { delete(s, item) } return s } // Has returns true if and only if item is contained in the set. func (s Set[T]) Has(item T) bool { _, contained := s[item] return contained } // HasAll returns true if and only if all items are contained in the set. func (s Set[T]) HasAll(items ...T) bool { for _, item := range items { if !s.Has(item) { return false } } return true } // HasAny returns true if any items are contained in the set. func (s Set[T]) HasAny(items ...T) bool { for _, item := range items { if s.Has(item) { return true } } return false } // Difference returns a set of objects that are not in s2 // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s Set[T]) Difference(s2 Set[T]) Set[T] { result := New[T]() for key := range s { if !s2.Has(key) { result.Insert(key) } } return result } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 Set[T]) Union(s2 Set[T]) Set[T] { result := New[T]() for key := range s1 { result.Insert(key) } for key := range s2 { result.Insert(key) } return result } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 Set[T]) Intersection(s2 Set[T]) Set[T] { var walk, other Set[T] result := New[T]() if s1.Len() < s2.Len() { walk = s1 other = s2 } else { walk = s2 other = s1 } for key := range walk { if other.Has(key) { result.Insert(key) } } return result } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 Set[T]) IsSuperset(s2 Set[T]) bool { for item := range s2 { if !s1.Has(item) { return false } } return true } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 Set[T]) Equal(s2 Set[T]) bool { return len(s1) == len(s2) && s1.IsSuperset(s2) } type sortableSliceOfT[T comparable] []T func (s sortableSliceOfT[T]) Len() int { return len(s) } func (s sortableSliceOfT[T]) Less(i, j int) bool { return lessT(s[i], s[j]) } func (s sortableSliceOfT[T]) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // List returns the contents as a sorted Object slice. func (s Set[T]) List() []T { res := make(sortableSliceOfT[T], 0, len(s)) for key := range s { res = append(res, key) } sort.Sort(res) return []T(res) } // UnsortedList returns the slice with contents in random order. func (s Set[T]) UnsortedList() []T { res := make([]T, 0, len(s)) for key := range s { res = append(res, key) } return res } // Returns a single element from the set. func (s Set[T]) PopAny() (T, bool) { for key := range s { s.Delete(key) return key, true } var zeroValue T return zeroValue, false } // Len returns the size of the set. func (s Set[T]) Len() int { return len(s) } type LesserT[T comparable] interface { Less(a, b T) bool } func lessT[T comparable](lhs, rhs T) bool { jbl, err := json.Marshal(lhs) if err != nil { return false } jbr, err := json.Marshal(rhs) if err != nil { return false } return string(jbl) < string(jbr) } ================================================ FILE: go/container/set/set.interface.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 set import ( "encoding/json" "reflect" "sort" ) // sets.Object is a set of Objects, implemented via map[Object]struct{} for minimal memory consumption. type Object map[interface{}]Empty // NewObject creates a Object from a list of values. func NewObject(items ...interface{}) Object { ss := Object{} ss.Insert(items...) return ss } // ObjectKeySet creates a Object from a keys of a map[Object](? extends interface{}). // If the value passed in is not actually a map, this will panic. func KeySet(theMap interface{}) Object { v := reflect.ValueOf(theMap) ret := Object{} for _, keyValue := range v.MapKeys() { ret.Insert(keyValue.Interface().(Object)) } return ret } // Insert adds items to the set. func (s Object) Insert(items ...interface{}) Object { for _, item := range items { s[item] = Empty{} } return s } // Delete removes all items from the set. func (s Object) Delete(items ...interface{}) Object { for _, item := range items { delete(s, item) } return s } // Has returns true if and only if item is contained in the set. func (s Object) Has(item interface{}) bool { _, contained := s[item] return contained } // HasAll returns true if and only if all items are contained in the set. func (s Object) HasAll(items ...interface{}) bool { for _, item := range items { if !s.Has(item) { return false } } return true } // HasAny returns true if any items are contained in the set. func (s Object) HasAny(items ...interface{}) bool { for _, item := range items { if s.Has(item) { return true } } return false } // Difference returns a set of objects that are not in s2 // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s Object) Difference(s2 Object) Object { result := NewObject() for key := range s { if !s2.Has(key) { result.Insert(key) } } return result } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 Object) Union(s2 Object) Object { result := NewObject() for key := range s1 { result.Insert(key) } for key := range s2 { result.Insert(key) } return result } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 Object) Intersection(s2 Object) Object { var walk, other Object result := NewObject() if s1.Len() < s2.Len() { walk = s1 other = s2 } else { walk = s2 other = s1 } for key := range walk { if other.Has(key) { result.Insert(key) } } return result } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 Object) IsSuperset(s2 Object) bool { for item := range s2 { if !s1.Has(item) { return false } } return true } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 Object) Equal(s2 Object) bool { return len(s1) == len(s2) && s1.IsSuperset(s2) } type sortableSliceOfObject []interface{} func (s sortableSliceOfObject) Len() int { return len(s) } func (s sortableSliceOfObject) Less(i, j int) bool { return lessObject(s[i], s[j]) } func (s sortableSliceOfObject) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // List returns the contents as a sorted Object slice. func (s Object) List() []interface{} { res := make(sortableSliceOfObject, 0, len(s)) for key := range s { res = append(res, key) } sort.Sort(res) return []interface{}(res) } // UnsortedList returns the slice with contents in random order. func (s Object) UnsortedList() []interface{} { res := make([]interface{}, 0, len(s)) for key := range s { res = append(res, key) } return res } // Returns a single element from the set. func (s Object) PopAny() (interface{}, bool) { for key := range s { s.Delete(key) return key, true } var zeroValue Object return zeroValue, false } // Len returns the size of the set. func (s Object) Len() int { return len(s) } type Lesser interface { Less(a interface{}, b interface{}) bool } /* func lessObject(lhs, rhs interface{}) bool { if lhs == nil { return false } if rhs == nil { return true } switch lhs := lhs.(type) { case nil: return false case *string: rhs, ok := rhs.(*string) if !ok { return false } return lhs != nil && rhs != nil && *lhs < *rhs case *[]byte: rhs, ok := rhs.(*[]byte) if !ok { return false } return lhs != nil && rhs != nil && string(*lhs) < string(*rhs) case *int: rhs, ok := rhs.(*int) if !ok { return false } return lhs != nil && rhs != nil && *lhs < *rhs case *int32: rhs, ok := rhs.(*int32) if !ok { return false } return lhs != nil && rhs != nil && *lhs < *rhs case *uint32: rhs, ok := rhs.(*uint32) if !ok { return false } return lhs != nil && rhs != nil && *lhs < *rhs case *int64: rhs, ok := rhs.(*int64) if !ok { return false } return lhs != nil && rhs != nil && *lhs < *rhs case *uint64: rhs, ok := rhs.(*uint64) if !ok { return false } return lhs != nil && rhs != nil && *lhs < *rhs case *float32: rhs, ok := rhs.(*float32) if !ok { return false } return lhs != nil && rhs != nil && *lhs < *rhs case *float64: rhs, ok := rhs.(*float64) if !ok { return false } return lhs != nil && rhs != nil && *lhs < *rhs default: var ll Lesser ll, ok = lhs.(Lesser) if !ok { } var err error jb, err = json.Marshal(v) if err != nil { return nil, fmt.Errorf("jsonpb.Marshal: %v", err) } } return false } */ func lessObject(lhs, rhs interface{}) bool { jbl, err := json.Marshal(lhs) if err != nil { return false } jbr, err := json.Marshal(rhs) if err != nil { return false } return string(jbl) < string(jbr) } /* func LessObject(lhs, rhs interface{}) bool { jbl, err := json.Marshal(lhs) if err != nil { return false } jbr, err := json.Marshal(rhs) if err != nil { return false } return string(jbl) < string(jbr) } */ ================================================ FILE: go/container/set/set_interface_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 set_test import ( "testing" set_ "github.com/kaydxh/golang/go/container/set" ) func TestSetInsert(t *testing.T) { s := set_.NewObject("10", "2", "5") s.Insert("a", "d", "e") if len(s) != 5 { t.Errorf("Expected len=5: %d", len(s)) } if !s.Has("a") || !s.Has("b") || !s.Has("c") || !s.Has("d") || !s.Has("e") { t.Errorf("UnExpected contents: %#v", s) } //%v output value //map[a:{} b:{} c:{} d:{} e:{}] t.Logf("s: %v", s) //%+v output field name + value //map[a:{} b:{} c:{} d:{} e:{}] t.Logf("s: %+v", s) //%#v output struct name + field name + value //set.Object{"a":set.Empty{}, "b":set.Empty{}, "c":set.Empty{}, "d":set.Empty{}, "e":set.Empty{}} t.Logf("s: %#v", s) //[a b c d e] t.Logf("s: %v", s.List()) } func TestSetEquals(t *testing.T) { a := set_.NewObject("1", "2") b := set_.NewObject("2", "1") if !a.Equal(b) { t.Errorf("Expected to be equal: %v vs %v", a, b) } //It is a set; duplicates are ignored b = set_.NewObject("2", "1", "1") if !a.Equal(b) { t.Errorf("Expected to be equal: %v vs %v", a, b) } } func TestSetUnion(t *testing.T) { tests := []struct { s1 set_.Object s2 set_.Object expected set_.Object }{ { set_.NewObject("1", "2", "3", "4"), set_.NewObject("3", "4", "5", "6"), set_.NewObject("1", "2", "3", "4", "5", "6"), }, { set_.NewObject("1", "2", "3", "4"), set_.NewObject(), set_.NewObject("1", "2", "3", "4"), }, { set_.NewObject(), set_.NewObject("1", "2", "3", "4"), set_.NewObject("1", "2", "3", "4"), }, { set_.NewObject(), set_.NewObject(), set_.NewObject(), }, } for _, test := range tests { union := test.s1.Union(test.s2) if union.Len() != test.expected.Len() { t.Errorf("Expected union.Len()=%d but got %d", test.expected.Len(), union.Len()) } if !union.Equal(test.expected) { t.Errorf( "Expected union.Equal(expected) but not true. union:%v expected:%v", union.List(), test.expected.List(), ) } } } func TestSetIntersection(t *testing.T) { tests := []struct { s1 set_.Object s2 set_.Object expected set_.Object }{ { set_.NewObject("1", "2", "3", "4"), set_.NewObject("3", "4", "5", "6"), set_.NewObject("3", "4"), }, { set_.NewObject("1", "2", "3", "4"), set_.NewObject("1", "2", "3", "4"), set_.NewObject("1", "2", "3", "4"), }, { set_.NewObject("1", "2", "3", "4"), set_.NewObject(), set_.NewObject(), }, { set_.NewObject(), set_.NewObject("1", "2", "3", "4"), set_.NewObject(), }, { set_.NewObject(), set_.NewObject(), set_.NewObject(), }, } for _, test := range tests { intersection := test.s1.Intersection(test.s2) if intersection.Len() != test.expected.Len() { t.Errorf("Expected intersection.Len()=%d but got %d", test.expected.Len(), intersection.Len()) } if !intersection.Equal(test.expected) { t.Errorf( "Expected intersection.Equal(expected) but not true. intersection:%v expected:%v", intersection.List(), test.expected.List(), ) } } } ================================================ FILE: go/container/set/set_string.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 set import ( "reflect" "sort" ) type Empty struct{} // sets.String is a set of strings, implemented via map[string]struct{} for minimal memory consumption. type String map[string]Empty // NewString creates a String from a list of values. func NewString(items ...string) String { ss := String{} ss.Insert(items...) return ss } // StringKeySet creates a String from a keys of a map[string](? extends interface{}). // If the value passed in is not actually a map, this will panic. func StringKeySet(theMap interface{}) String { v := reflect.ValueOf(theMap) ret := String{} for _, keyValue := range v.MapKeys() { ret.Insert(keyValue.Interface().(string)) } return ret } // Insert adds items to the set. func (s String) Insert(items ...string) String { for _, item := range items { s[item] = Empty{} } return s } // Delete removes all items from the set. func (s String) Delete(items ...string) String { for _, item := range items { delete(s, item) } return s } // Has returns true if and only if item is contained in the set. func (s String) Has(item string) bool { _, contained := s[item] return contained } // HasAll returns true if and only if all items are contained in the set. func (s String) HasAll(items ...string) bool { for _, item := range items { if !s.Has(item) { return false } } return true } // HasAny returns true if any items are contained in the set. func (s String) HasAny(items ...string) bool { for _, item := range items { if s.Has(item) { return true } } return false } // Difference returns a set of objects that are not in s2 // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s String) Difference(s2 String) String { result := NewString() for key := range s { if !s2.Has(key) { result.Insert(key) } } return result } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 String) Union(s2 String) String { result := NewString() for key := range s1 { result.Insert(key) } for key := range s2 { result.Insert(key) } return result } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 String) Intersection(s2 String) String { var walk, other String result := NewString() if s1.Len() < s2.Len() { walk = s1 other = s2 } else { walk = s2 other = s1 } for key := range walk { if other.Has(key) { result.Insert(key) } } return result } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 String) IsSuperset(s2 String) bool { for item := range s2 { if !s1.Has(item) { return false } } return true } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 String) Equal(s2 String) bool { return len(s1) == len(s2) && s1.IsSuperset(s2) } type sortableSliceOfString []string func (s sortableSliceOfString) Len() int { return len(s) } func (s sortableSliceOfString) Less(i, j int) bool { return lessString(s[i], s[j]) } func (s sortableSliceOfString) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // List returns the contents as a sorted string slice. func (s String) List() []string { res := make(sortableSliceOfString, 0, len(s)) for key := range s { res = append(res, key) } sort.Sort(res) return []string(res) } // UnsortedList returns the slice with contents in random order. func (s String) UnsortedList() []string { res := make([]string, 0, len(s)) for key := range s { res = append(res, key) } return res } // Returns a single element from the set. func (s String) PopAny() (string, bool) { for key := range s { s.Delete(key) return key, true } var zeroValue string return zeroValue, false } // Len returns the size of the set. func (s String) Len() int { return len(s) } func lessString(lhs, rhs string) bool { return lhs < rhs } ================================================ FILE: go/container/set/set_string_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 set_test import ( "testing" set_ "github.com/kaydxh/golang/go/container/set" ) func TestStringSetInsert(t *testing.T) { s := set_.NewString("a", "b", "c") s.Insert("a", "d", "e") if len(s) != 5 { t.Errorf("Expected len=5: %d", len(s)) } if !s.Has("a") || !s.Has("b") || !s.Has("c") || !s.Has("d") || !s.Has("e") { t.Errorf("UnExpected contents: %#v", s) } //%v output value //map[a:{} b:{} c:{} d:{} e:{}] t.Logf("s: %v", s) //%+v output field name + value //map[a:{} b:{} c:{} d:{} e:{}] t.Logf("s: %+v", s) //%#v output struct name + field name + value //set.String{"a":set.Empty{}, "b":set.Empty{}, "c":set.Empty{}, "d":set.Empty{}, "e":set.Empty{}} t.Logf("s: %#v", s) //[a b c d e] t.Logf("s: %v", s.List()) } func TestStringSetEquals(t *testing.T) { a := set_.NewString("1", "2") b := set_.NewString("2", "1") if !a.Equal(b) { t.Errorf("Expected to be equal: %v vs %v", a, b) } //It is a set; duplicates are ignored b = set_.NewString("2", "1", "1") if !a.Equal(b) { t.Errorf("Expected to be equal: %v vs %v", a, b) } } func TestStringSetUnion(t *testing.T) { tests := []struct { s1 set_.String s2 set_.String expected set_.String }{ { set_.NewString("1", "2", "3", "4"), set_.NewString("3", "4", "5", "6"), set_.NewString("1", "2", "3", "4", "5", "6"), }, { set_.NewString("1", "2", "3", "4"), set_.NewString(), set_.NewString("1", "2", "3", "4"), }, { set_.NewString(), set_.NewString("1", "2", "3", "4"), set_.NewString("1", "2", "3", "4"), }, { set_.NewString(), set_.NewString(), set_.NewString(), }, } for _, test := range tests { union := test.s1.Union(test.s2) if union.Len() != test.expected.Len() { t.Errorf("Expected union.Len()=%d but got %d", test.expected.Len(), union.Len()) } if !union.Equal(test.expected) { t.Errorf( "Expected union.Equal(expected) but not true. union:%v expected:%v", union.List(), test.expected.List(), ) } } } func TestStringSetIntersection(t *testing.T) { tests := []struct { s1 set_.String s2 set_.String expected set_.String }{ { set_.NewString("1", "2", "3", "4"), set_.NewString("3", "4", "5", "6"), set_.NewString("3", "4"), }, { set_.NewString("1", "2", "3", "4"), set_.NewString("1", "2", "3", "4"), set_.NewString("1", "2", "3", "4"), }, { set_.NewString("1", "2", "3", "4"), set_.NewString(), set_.NewString(), }, { set_.NewString(), set_.NewString("1", "2", "3", "4"), set_.NewString(), }, { set_.NewString(), set_.NewString(), set_.NewString(), }, } for _, test := range tests { intersection := test.s1.Intersection(test.s2) if intersection.Len() != test.expected.Len() { t.Errorf("Expected intersection.Len()=%d but got %d", test.expected.Len(), intersection.Len()) } if !intersection.Equal(test.expected) { t.Errorf( "Expected intersection.Equal(expected) but not true. intersection:%v expected:%v", intersection.List(), test.expected.List(), ) } } } ================================================ FILE: go/container/set/set_test.go ================================================ package set_test import ( "testing" set_ "github.com/kaydxh/golang/go/container/set" ) func TestGenericSetNew(t *testing.T) { s := set_.New[int]() s.Insert(2) t.Logf("s: %v", s) } func TestGenericSetInsert(t *testing.T) { s := set_.New("10", "2", "5") s.Insert("a", "d", "e") if len(s) != 5 { t.Errorf("Expected len=5: %d", len(s)) } if !s.Has("a") || !s.Has("b") || !s.Has("c") || !s.Has("d") || !s.Has("e") { t.Errorf("UnExpected contents: %#v", s) } //%v output value //map[a:{} b:{} c:{} d:{} e:{}] t.Logf("s: %v", s) //%+v output field name + value //map[a:{} b:{} c:{} d:{} e:{}] t.Logf("s: %+v", s) //%#v output struct name + field name + value //set.Object{"a":set.Empty{}, "b":set.Empty{}, "c":set.Empty{}, "d":set.Empty{}, "e":set.Empty{}} t.Logf("s: %#v", s) //[a b c d e] t.Logf("s: %v", s.List()) } func TestGenericSetEquals(t *testing.T) { a := set_.New("1", "2") b := set_.New("2", "1") if !a.Equal(b) { t.Errorf("Expected to be equal: %v vs %v", a, b) } //It is a set; duplicates are ignored b = set_.New("2", "1", "1") if !a.Equal(b) { t.Errorf("Expected to be equal: %v vs %v", a, b) } } func TestGenericSetUnion(t *testing.T) { tests := []struct { s1 set_.Set[string] s2 set_.Set[string] expected set_.Set[string] }{ { set_.New("1", "2", "3", "4"), set_.New("3", "4", "5", "6"), set_.New("1", "2", "3", "4", "5", "6"), }, { set_.New("1", "2", "3", "4"), set_.New[string](), set_.New("1", "2", "3", "4"), }, { set_.New[string](), set_.New("1", "2", "3", "4"), set_.New("1", "2", "3", "4"), }, { set_.New[string](), set_.New[string](), set_.New[string](), }, } for _, test := range tests { union := test.s1.Union(test.s2) if union.Len() != test.expected.Len() { t.Errorf("Expected union.Len()=%d but got %d", test.expected.Len(), union.Len()) } if !union.Equal(test.expected) { t.Errorf( "Expected union.Equal(expected) but not true. union:%v expected:%v", union.List(), test.expected.List(), ) } } } ================================================ FILE: go/container/workqueue/queue.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 workqueue import ( "sync" ) type Interface interface { Add(item interface{}) Len() int Get() (item interface{}, shutdown bool) Done(item interface{}) ShutDown() ShuttingDown() bool } func NewQueue() *Type { t := &Type{ dirty: set{}, processing: set{}, cond: sync.NewCond(&sync.Mutex{}), } return t } // Type is a work queue (see the package comment). type Type struct { // queue defines the order in which we will work on items. Every // element of queue should be in the dirty set and not in the // processing set. queue []t // dirty defines all of the items that need to be processed. dirty set // Things that are currently being processed are in the processing set. // These things may be simultaneously in the dirty set. When we finish // processing something and remove it from this set, we'll check if // it's in the dirty set, and if so, add it to the queue. processing set cond *sync.Cond shuttingDown bool drain bool } type empty struct{} type t interface{} type set map[t]empty func (s set) has(item t) bool { _, exists := s[item] return exists } func (s set) insert(item t) { s[item] = empty{} } func (s set) delete(item t) { delete(s, item) } func (s set) len() int { return len(s) } // Add marks item as needing processing. func (q *Type) Add(item interface{}) { q.cond.L.Lock() defer q.cond.L.Unlock() if q.shuttingDown { return } if q.dirty.has(item) { return } q.dirty.insert(item) if q.processing.has(item) { return } q.queue = append(q.queue, item) q.cond.Signal() } func (q *Type) Len() int { q.cond.L.Lock() defer q.cond.L.Unlock() return len(q.queue) } func (q *Type) Get() (item interface{}, shutdown bool) { q.cond.L.Lock() defer q.cond.L.Unlock() for len(q.queue) == 0 && !q.shuttingDown { q.cond.Wait() } if len(q.queue) == 0 { // We must be shutting down. return nil, true } item = q.queue[0] // The underlying array still exists and reference this object, so the object will not be garbage collected. q.queue[0] = nil q.queue = q.queue[1:] q.processing.insert(item) q.dirty.delete(item) return item, false } func (q *Type) Done(item interface{}) { q.cond.L.Lock() defer q.cond.L.Unlock() q.processing.delete(item) if q.dirty.has(item) { q.queue = append(q.queue, item) q.cond.Signal() } else if q.processing.len() == 0 { q.cond.Signal() } } // ShutDown will cause q to ignore all new items added to it and // immediately instruct the worker goroutines to exit. func (q *Type) ShutDown() { q.setDrain(false) q.shutdown() } // ShutDownWithDrain will cause q to ignore all new items added to it. As soon // as the worker goroutines have "drained", i.e: finished processing and called // Done on all existing items in the queue; they will be instructed to exit and // ShutDownWithDrain will return. Hence: a strict requirement for using this is; // your workers must ensure that Done is called on all items in the queue once // the shut down has been initiated, if that is not the case: this will block // indefinitely. It is, however, safe to call ShutDown after having called // ShutDownWithDrain, as to force the queue shut down to terminate immediately // without waiting for the drainage. func (q *Type) ShutDownWithDrain() { q.setDrain(true) q.shutdown() for q.isProcessing() && q.shouldDrain() { q.waitForProcessing() } } // isProcessing indicates if there are still items on the work queue being // processed. It's used to drain the work queue on an eventual shutdown. func (q *Type) isProcessing() bool { q.cond.L.Lock() defer q.cond.L.Unlock() return q.processing.len() != 0 } // waitForProcessing waits for the worker goroutines to finish processing items // and call Done on them. func (q *Type) waitForProcessing() { q.cond.L.Lock() defer q.cond.L.Unlock() // Ensure that we do not wait on a queue which is already empty, as that // could result in waiting for Done to be called on items in an empty queue // which has already been shut down, which will result in waiting // indefinitely. if q.processing.len() == 0 { return } q.cond.Wait() } func (q *Type) setDrain(shouldDrain bool) { q.cond.L.Lock() defer q.cond.L.Unlock() q.drain = shouldDrain } func (q *Type) shouldDrain() bool { q.cond.L.Lock() defer q.cond.L.Unlock() return q.drain } func (q *Type) shutdown() { q.cond.L.Lock() defer q.cond.L.Unlock() q.shuttingDown = true q.cond.Broadcast() } func (q *Type) ShuttingDown() bool { q.cond.L.Lock() defer q.cond.L.Unlock() return q.shuttingDown } ================================================ FILE: go/container/workqueue/queue_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 workqueue_test import ( "sync" "testing" "time" workqueue_ "github.com/kaydxh/golang/go/container/workqueue" ) func TestBasic(t *testing.T) { testCases := []struct { queue *workqueue_.Type queueShutDown func(workqueue_.Interface) }{ { queue: workqueue_.NewQueue(), queueShutDown: workqueue_.Interface.ShutDown, }, } for _, testCase := range testCases { // Start producers const producers = 10 producerWG := sync.WaitGroup{} producerWG.Add(producers) for i := 0; i < producers; i++ { go func(i int) { defer producerWG.Done() for j := 0; j < 2; j++ { testCase.queue.Add(i) time.Sleep(time.Millisecond) } }(i) } // Start consumers const consumers = 10 consumerWG := sync.WaitGroup{} consumerWG.Add(consumers) for i := 0; i < consumers; i++ { go func(i int) { defer consumerWG.Done() for { item, quit := testCase.queue.Get() if quit { return } t.Logf("Woker %v: begin processing %v", i, item) time.Sleep(3 * time.Millisecond) t.Logf("Woker %v: done processing %v", i, item) testCase.queue.Done(item) } }(i) } producerWG.Wait() testCase.queueShutDown(testCase.queue) testCase.queue.Add("add after shutdown!") consumerWG.Wait() if testCase.queue.Len() != 0 { t.Errorf("Expected the queue to be empty, had: %v items", testCase.queue.Len()) } } } func TestReinsert(t *testing.T) { q := workqueue_.NewQueue() q.Add("foo") // Start processing i, _ := q.Get() if i != "foo" { t.Errorf("Expected %v, got %v", "foo", i) } // Add it back while processing q.Add(i) // Finish it up q.Done(i) // It should be back on the queue i, _ = q.Get() if i != "foo" { t.Errorf("Expected %v, got %v", "foo", i) } // Finish that one up q.Done(i) if a := q.Len(); a != 0 { t.Errorf("Expected queue to be empty. Has %v items", a) } } ================================================ FILE: go/context/context.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 context import ( "context" "fmt" "strconv" "time" ) // RequestIdKey is metadata key name for request ID const ( DefaultHTTPRequestIDKey = "X-Request-ID" DefaultHTTPTraceIDKey = "X-Traceid" ) func WithTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) { if timeout > 0 { return context.WithTimeout(ctx, timeout) } return ctx, func() {} } func ExtractStringFromContext(ctx context.Context, key string) string { if v, ok := ctx.Value(key).(string); ok { return v } return "" } func ExtractIntegerFromContext(ctx context.Context, key string) (int64, error) { v, ok := ctx.Value(key).(string) if !ok { return 0, fmt.Errorf("key[%v] value type is not string", key) } number, err := strconv.ParseInt(v, 10, 64) if err != nil { return 0, fmt.Errorf("key[%v] value type is not number: %v", key, err) } return number, nil } func ExtractFromContext(ctx context.Context, key string) string { switch value := ctx.Value(key).(type) { case string: if value != "" { return value } case []string: if len(value) > 0 { return value[0] } default: return "" } return "" } func UpdateContext(ctx context.Context, key string, values map[string]interface{}) error { currentValues, ok := ctx.Value(key).(map[string]interface{}) if ok { for k, v := range values { currentValues[k] = v } return nil } return fmt.Errorf("key[%v] is not exist in context", key) } func SetPairContext(ctx context.Context, key, value string) context.Context { return context.WithValue(ctx, key, value) } func AppendContext(ctx context.Context, key string, values ...string) context.Context { currentValues, _ := ctx.Value(key).([]string) currentValues = append(currentValues, values...) return context.WithValue(ctx, key, currentValues) } func WithContextRequestId(ctx context.Context, id string) context.Context { return context.WithValue(ctx, DefaultHTTPRequestIDKey, id) } func ExtractRequestIDFromContext(ctx context.Context) string { if v, ok := ctx.Value(DefaultHTTPRequestIDKey).(string); ok { return v } return "" } func ExtractTraceIDFromContext(ctx context.Context) string { if v, ok := ctx.Value(DefaultHTTPTraceIDKey).(string); ok { return v } return "" } ================================================ FILE: go/context/context_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 context_test import ( "context" "fmt" "testing" "time" context_ "github.com/kaydxh/golang/go/context" ) func withField(ctx context.Context) { ctx = context.WithValue(ctx, "abc", "abc") fmt.Printf("context: %+v\n", ctx) } func TestContext(t *testing.T) { ctx := context.Background() t.Logf("context: %v", ctx) withField(ctx) t.Logf("context: %v", ctx) } func doA(ctx context.Context) { { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, time.Second) defer cancel() } timer := time.NewTimer(3 * time.Second) defer timer.Stop() select { case <-ctx.Done(): fmt.Println("doA timeout") case <-timer.C: fmt.Println("doA finish") } } func doB(ctx context.Context) { { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, 10*time.Second) defer cancel() } timer := time.NewTimer(3 * time.Second) defer timer.Stop() select { case <-ctx.Done(): fmt.Println("doB timeout") case <-timer.C: fmt.Println("doB finish") } } func TestContextTimeout(t *testing.T) { ctx := context.Background() doA(ctx) doB(ctx) } func TestExtractIntegerFromContext(t *testing.T) { ctx := context.Background() testCases := []struct { key string value string expected string }{ { key: "test-1", value: "123", }, { key: "test-2", value: "test-123", }, } for _, testCase := range testCases { t.Run(testCase.key, func(t *testing.T) { ctx = context_.SetPairContext(ctx, testCase.key, testCase.value) number, err := context_.ExtractIntegerFromContext(ctx, testCase.key) if err != nil { t.Errorf("expect nil, got %v", err) return } t.Logf("extract value %v by key %v ", number, testCase.key) }) } } func TestExtractStringFromContext(t *testing.T) { ctx := context.Background() testCases := []struct { key string value string expected string }{ { key: "test-1", value: "123", }, { key: "test-2", value: "test-123", }, } for _, testCase := range testCases { t.Run(testCase.key, func(t *testing.T) { ctx = context_.SetPairContext(ctx, testCase.key, testCase.value) value := context_.ExtractStringFromContext(ctx, testCase.key) t.Logf("extract value %v by key %v ", value, testCase.key) }) } } ================================================ FILE: go/crypto/aes/aes_cbc.go ================================================ /* MIT License Copyright (c) 2020 kay 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 aes import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "io" ) func AesCbcEncrypt(plainText, key []byte) ([]byte, error) { if len(key) != 16 && len(key) != 32 { return nil, ErrKeyLength } block, err := aes.NewCipher(key) if err != nil { return nil, err } paddingText := pad(plainText, aes.BlockSize) cipherText := make([]byte, aes.BlockSize+len(paddingText)) iv := cipherText[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return nil, err } blockMode := cipher.NewCBCEncrypter(block, iv) blockMode.CryptBlocks(cipherText[aes.BlockSize:], paddingText) return cipherText, nil } func AesCbcDecrypt(cipherText, key []byte) ([]byte, error) { if len(key) != 16 && len(key) != 24 { return nil, ErrKeyLength } if len(cipherText) < aes.BlockSize { return nil, ErrCipherTextLength } block, err := aes.NewCipher(key) if err != nil { return nil, err } iv := cipherText[:aes.BlockSize] cb := cipherText[aes.BlockSize:] blockMode := cipher.NewCBCDecrypter(block, iv) blockMode.CryptBlocks(cb, cb) plainText, err := unpad(cb) if err != nil { return nil, err } return plainText, nil } func pad(plainText []byte, blockSize int) []byte { padding := blockSize - (len(plainText) % blockSize) padText := bytes.Repeat([]byte{byte(padding)}, padding) newText := append(plainText, padText...) return newText } func unpad(plainText []byte) ([]byte, error) { length := len(plainText) unpadding := int(plainText[length-1]) if unpadding > length { return nil, ErrPaddingSize } return plainText[:length-unpadding], nil } ================================================ FILE: go/crypto/aes/aes_cbc_test.go ================================================ /* MIT License Copyright (c) 2020 kay 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 aes_test import ( "fmt" "testing" "flag" aes_ "github.com/kaydxh/golang/go/crypto/aes" io_ "github.com/kaydxh/golang/go/io" ) func TestAesCbcEncryptDecrypt(t *testing.T) { plainText := []byte("Hello World") fmt.Println("plainText: ", string(plainText)) key := []byte("daW3eDgPEa9TjknE") cryptText, err := aes_.AesCbcEncrypt(plainText, key) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println("cryptText: ", string(cryptText)) newplainText, err := aes_.AesCbcDecrypt(cryptText, key) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println("newplainText: ", string(newplainText)) if string(newplainText) != string(plainText) { t.Errorf("newplainText not equal plainText") } } // build: go test -c aes_cbc_test.go -o decrypt_tool // run: ./decrypt_tool -test.v --test.run TestAesCbcDecrypt -srcePath=1.jpg -destPath=2.jpg var ( srcePath = flag.String("srcePath", "", "source encrypt image path") destPath = flag.String("destPath", "./decryptImage.jpg", "dest decrypt image path") ) func TestAesCbcDecrypt(t *testing.T) { cryptText, err := io_.ReadFile(*srcePath) if err != nil { t.Errorf("expect nil, got %v", err) return } key := []byte("daW3eDgPEa9TjknE") newplainText, err := aes_.AesCbcDecrypt(cryptText, key) if err != nil { t.Errorf("expect nil, got %v", err) } io_.WriteFile(*destPath, newplainText, false) } ================================================ FILE: go/crypto/aes/error.go ================================================ /* MIT License Copyright (c) 2020 kay 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 aes import "errors" var ( ErrKeyLength = errors.New("err key lenght") ErrPaddingSize = errors.New("err padding size") ErrCipherTextLength = errors.New("err cipherText lenght") ) ================================================ FILE: go/crypto/md5/md5.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 md5 import ( "bytes" "crypto/md5" "encoding/hex" "io" "os" os_ "github.com/kaydxh/golang/go/os" ) func SumBytes(b []byte) string { h := md5.New() h.Write(b) return hex.EncodeToString(h.Sum(nil)) } func SumString(s string) string { return SumBytes([]byte(s)) } func SumReader(r io.Reader) (string, error) { h := md5.New() if _, err := io.Copy(h, r); err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil } func SumReaderN(r io.Reader, n int64) (string, error) { h := md5.New() if _, err := io.CopyN(h, r, n); err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil } func SumReaderAt(r io.ReaderAt, offset, length int64) (string, error) { h := md5.New() buf := make([]byte, 1024) var total int64 for total < length { n, err := r.ReadAt(buf, offset) if err == nil || err == io.EOF { if n > 0 { _, tmpErr := io.CopyN(h, bytes.NewReader(buf), int64(n)) if tmpErr != nil { return "", tmpErr } offset += int64(n) total += int64(n) } if err == io.EOF { break } } else { return "", err } } return hex.EncodeToString(h.Sum(nil)), nil } func SumFile(fileName string) (string, error) { file, err := os_.OpenFile(fileName, true) if err != nil { return "", err } defer file.Close() return SumReader(file) } func SumFileAt(fileName string, offset int64, length int64) (string, error) { file, err := os_.OpenAll(fileName, os.O_RDWR, os.ModePerm) if err != nil { return "", err } defer file.Close() return SumReaderAt(file, offset, length) } ================================================ FILE: go/crypto/md5/md5_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 md5_test import ( "fmt" "io/ioutil" "os" "testing" md5_ "github.com/kaydxh/golang/go/crypto/md5" "gotest.tools/assert" ) func TestMd5File(t *testing.T) { file, err := ioutil.TempFile(".", "file") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(file.Name()) strContext := "hello world" // n, err := io.WriteString(file, "hello world") n, err := file.Write([]byte(strContext)) if err != nil { t.Errorf("expect nil, got %v", err) } assert.Equal(t, len(strContext), n) fmt.Printf("fileName: %v, n: %v\n", file.Name(), n) sum, err := md5_.SumFile(file.Name()) if err != nil { t.Errorf("expect nil, got %v", err) } assert.Equal(t, sum, md5_.SumString(strContext)) } func TestMd5FileAt(t *testing.T) { file, err := ioutil.TempFile(".", "file") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(file.Name()) testCases := []struct { name string words []byte expected string }{ { name: "write one word", words: []byte("test1"), expected: "test1", }, { name: "write one word", words: []byte("test2"), expected: "test2", }, { name: "write one word", words: []byte("test3"), expected: "test3", }, } var offset int64 for i, testCase := range testCases { _, err := file.Write(testCase.words) if err != nil { t.Errorf("expect nil, got %v", err) } if i > 0 { offset += int64(len(testCases[i-1].words)) } fmt.Printf("i: %d, offset: %v, testCase: %s\n", i, offset, testCase.words) sum, err := md5_.SumFileAt(file.Name(), offset, int64(len(testCase.words))) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println("sum: ", sum) assert.Equal(t, sum, md5_.SumBytes(testCase.words)) } } ================================================ FILE: go/crypto/sha256/sha256.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 sha256 import ( "bytes" "crypto/sha256" "encoding/hex" "io" "os" os_ "github.com/kaydxh/golang/go/os" ) func SumBytes(b []byte) string { h := sha256.New() h.Write(b) return hex.EncodeToString(h.Sum(nil)) } func SumString(s string) string { return SumBytes([]byte(s)) } func SumReader(r io.Reader) (string, error) { h := sha256.New() if _, err := io.Copy(h, r); err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil } func SumReaderN(r io.Reader, n int64) (string, error) { h := sha256.New() if _, err := io.CopyN(h, r, n); err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil } func SumReaderAt(r io.ReaderAt, offset, length int64) (string, error) { h := sha256.New() buf := make([]byte, 1024) var total int64 for total < length { n, err := r.ReadAt(buf, offset) if err == nil || err == io.EOF { if n > 0 { _, tmpErr := io.CopyN(h, bytes.NewReader(buf), int64(n)) if tmpErr != nil { return "", tmpErr } offset += int64(n) total += int64(n) } if err == io.EOF { break } } else { return "", err } } return hex.EncodeToString(h.Sum(nil)), nil } func SumFile(fileName string) (string, error) { file, err := os_.OpenFile(fileName, true) if err != nil { return "", err } defer file.Close() return SumReader(file) } func SumFileAt(fileName string, offset int64, length int64) (string, error) { file, err := os_.OpenAll(fileName, os.O_RDWR, os.ModePerm) if err != nil { return "", err } defer file.Close() return SumReaderAt(file, offset, length) } ================================================ FILE: go/crypto/sha256/sha256_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 sha256_test import ( "fmt" "io/ioutil" "os" "testing" sha256_ "github.com/kaydxh/golang/go/crypto/sha256" "gotest.tools/assert" ) func TestSha256File(t *testing.T) { file, err := ioutil.TempFile(".", "file") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(file.Name()) strContext := "hello world" // n, err := io.WriteString(file, "hello world") n, err := file.Write([]byte(strContext)) if err != nil { t.Errorf("expect nil, got %v", err) } assert.Equal(t, len(strContext), n) fmt.Printf("fileName: %v, n: %v\n", file.Name(), n) sum, err := sha256_.SumFile(file.Name()) if err != nil { t.Errorf("expect nil, got %v", err) } assert.Equal(t, sum, sha256_.SumString(strContext)) } func TestSha256FileAt(t *testing.T) { file, err := ioutil.TempFile(".", "file") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(file.Name()) testCases := []struct { name string words []byte expected string }{ { name: "write one word", words: []byte("test1"), expected: "test1", }, { name: "write one word", words: []byte("test2"), expected: "test2", }, { name: "write one word", words: []byte("test3"), expected: "test3", }, } var offset int64 for i, testCase := range testCases { _, err := file.Write(testCase.words) if err != nil { t.Errorf("expect nil, got %v", err) } if i > 0 { offset += int64(len(testCases[i-1].words)) } fmt.Printf("i: %d, offset: %v, testCase: %s\n", i, offset, testCase.words) sum, err := sha256_.SumFileAt(file.Name(), offset, int64(len(testCase.words))) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println("sum: ", sum) assert.Equal(t, sum, sha256_.SumBytes(testCase.words)) } } ================================================ FILE: go/doc.go ================================================ package _go ================================================ FILE: go/encoding/base64/base64.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 base64 import ( "encoding/base64" "fmt" ) func EncodeString(v string) string { return base64.StdEncoding.EncodeToString([]byte(v)) } func DecodeString(v string) (string, error) { data, err := base64.StdEncoding.DecodeString(v) if err != nil { return "", fmt.Errorf("base64 decode failed: %v", err) } return string(data), nil } func EncodeURL(v string) string { return base64.URLEncoding.EncodeToString([]byte(v)) } func DecodeURL(v string) (string, error) { data, err := base64.URLEncoding.DecodeString(v) if err != nil { return "", fmt.Errorf("base64 decode url failed: %v", err) } return string(data), nil } ================================================ FILE: go/encoding/base64/base64_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 base64_test import ( "encoding/binary" "fmt" "math" "testing" io_ "github.com/kaydxh/golang/go/io" base64_ "github.com/kaydxh/golang/go/encoding/base64" "gotest.tools/v3/assert" ) func TestString(t *testing.T) { testCases := []struct { name string expected string }{ { name: "hello word", expected: "", }, { name: "http://12306.com?a=%b", expected: "", }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { encoded := base64_.EncodeString(testCase.name) t.Logf("base64 encode : %v", encoded) decoded, err := base64_.DecodeString(encoded) if err != nil { t.Fatalf("failed to decode string, err: %v", err) } assert.Equal(t, testCase.name, decoded) }) } /* content := "hello word" encoded := base64_.EncodeString(content) t.Logf("base64 encode : %v", encoded) decoded, err := base64_.DecodeString(encoded) if err != nil { t.Fatalf("failed to decode string, err: %v", err) } t.Logf("base64 decode : %v", decoded) */ //assert.Equal(t, content, decoded) } func TestURL(t *testing.T) { testCases := []struct { name string expected string }{ { name: `http://baidu.com?a=10&b="hello"`, expected: "", }, { name: "http://12306.com?a=%b", expected: "", }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { encoded := base64_.EncodeURL(testCase.name) t.Logf("base64 encode : %v", encoded) decoded, err := base64_.DecodeURL(encoded) if err != nil { t.Fatalf("failed to decode url, err: %v", err) } assert.Equal(t, testCase.name, decoded) }) } } func TestDecodeString(t *testing.T) { testCases := []struct { value string expected string }{ { value: "PeNT+D5jU/g=", expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { decoded, err := base64_.DecodeString(testCase.value) if err != nil { t.Fatalf("failed to decode string, err: %v", err) } t.Logf("decode string len: %v, value len: %v", len(decoded), len(testCase.value)) j := 0 for i := 0; i < len(decoded); i += 4 { bits := binary.LittleEndian.Uint32([]byte(decoded[i : i+4])) fmt.Printf("%f ", math.Float32frombits(bits)) j++ } fmt.Printf("j=%v", j) }) } } func TestDecodeFile(t *testing.T) { testCases := []struct { value string expected string }{ { value: "./1.txt", expected: "", }, } for i, testCase := range testCases { encodedValue, err := io_.ReadFile(testCase.value) if err != nil { t.Fatalf("failed to read file: %v, err: %v", testCase.value, err) } t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { decoded, err := base64_.DecodeString(string(encodedValue)) if err != nil { t.Fatalf("failed to decode string, err: %v", err) } t.Logf("decode string len: %v, value len: %v", len(decoded), len(testCase.value)) io_.WriteFile(testCase.value+".mp4", []byte(decoded), false) }) } } ================================================ FILE: go/encoding/hash/hash.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 hash import "hash/crc32" func HashCode(s string) uint32 { return crc32.ChecksumIEEE([]byte(s)) } ================================================ FILE: go/encoding/hash/hash_test.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 hash_test import ( "fmt" "testing" hash_ "github.com/kaydxh/golang/go/encoding/hash" ) func TestHashCode(t *testing.T) { testCases := []struct { value string expected string }{ { value: "0", expected: "", }, { value: "1", expected: "", }, { value: "2", expected: "", }, { value: "10", expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { hashCode := hash_.HashCode(testCase.value) t.Logf("%v hash code %v, mod10 %v", testCase.value, hashCode, hashCode%10) }) } } ================================================ FILE: go/encoding/jwt/jwt.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 jwt 提供轻量级的 JWT(JSON Web Token)解析工具。 // // 注意:本包仅解析 JWT payload,不验证签名。适用于以下场景: // - Token 来自可信的服务端(server-to-server) // - 仅需提取 claims 中的字段用于日志、路由等非鉴权用途 // // 如果 Token 来自不可信客户端或用于鉴权决策,必须使用带签名验证的 JWT 库。 package jwt import ( "encoding/base64" "encoding/json" "fmt" "strings" ) // ParsePayload 解析 JWT token 的 payload 部分,返回 claims map。 // 不验证签名,仅做 base64url 解码 + JSON 反序列化。 // token 格式必须为标准 JWT 三段式:header.payload.signature。 func ParsePayload(token string) (map[string]interface{}, error) { if token == "" { return nil, fmt.Errorf("jwt: empty token") } parts := strings.Split(token, ".") if len(parts) != 3 { return nil, fmt.Errorf("jwt: invalid token format, expected 3 parts, got %d", len(parts)) } // base64url 解码 payload(JWT 标准使用无 padding 的 base64url) decoded, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil { // 兼容带 padding 的 base64url decoded, err = base64.URLEncoding.DecodeString(padBase64(parts[1])) if err != nil { // 最后尝试标准 base64(某些非标准实现可能使用) decoded, err = base64.StdEncoding.DecodeString(padBase64(parts[1])) if err != nil { return nil, fmt.Errorf("jwt: decode payload: %w", err) } } } var claims map[string]interface{} if err := json.Unmarshal(decoded, &claims); err != nil { return nil, fmt.Errorf("jwt: unmarshal payload: %w", err) } return claims, nil } // GetClaimString 从 claims 中安全提取字符串类型的字段值。 // 如果字段不存在或类型不是 string,返回空字符串。 func GetClaimString(claims map[string]interface{}, key string) string { if claims == nil { return "" } v, ok := claims[key].(string) if !ok { return "" } return v } // GetClaimFloat64 从 claims 中安全提取数值类型的字段值。 // JSON 数字默认反序列化为 float64,如果字段不存在或类型不匹配,返回 0。 func GetClaimFloat64(claims map[string]interface{}, key string) float64 { if claims == nil { return 0 } v, ok := claims[key].(float64) if !ok { return 0 } return v } // padBase64 为 base64 字符串补齐 padding。 func padBase64(s string) string { switch len(s) % 4 { case 2: return s + "==" case 3: return s + "=" } return s } ================================================ FILE: go/encoding/jwt/jwt_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 jwt import ( "testing" ) func TestParsePayload(t *testing.T) { tests := []struct { name string token string wantErr bool check func(claims map[string]interface{}) bool }{ { name: "空 token", token: "", wantErr: true, }, { name: "非法格式(只有一段)", token: "abc", wantErr: true, }, { name: "非法格式(只有两段)", token: "abc.def", wantErr: true, }, { name: "合法 JWT(base64url 无 padding)", token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYWxpY2UiLCJleHAiOjE3MTk5OTk5OTl9.signature", check: func(claims map[string]interface{}) bool { return GetClaimString(claims, "user_id") == "alice" }, }, { name: "payload 为空 JSON 对象", token: "eyJhbGciOiJIUzI1NiJ9.e30.signature", check: func(claims map[string]interface{}) bool { return len(claims) == 0 }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { claims, err := ParsePayload(tt.token) if (err != nil) != tt.wantErr { t.Errorf("ParsePayload() error = %v, wantErr %v", err, tt.wantErr) return } if tt.check != nil && !tt.check(claims) { t.Errorf("ParsePayload() claims check failed, claims = %v", claims) } }) } } func TestGetClaimString(t *testing.T) { claims := map[string]interface{}{ "user_id": "bob", "count": float64(42), } if got := GetClaimString(claims, "user_id"); got != "bob" { t.Errorf("GetClaimString(user_id) = %q, want %q", got, "bob") } if got := GetClaimString(claims, "missing"); got != "" { t.Errorf("GetClaimString(missing) = %q, want empty", got) } if got := GetClaimString(claims, "count"); got != "" { t.Errorf("GetClaimString(count) = %q, want empty (type mismatch)", got) } if got := GetClaimString(nil, "user_id"); got != "" { t.Errorf("GetClaimString(nil) = %q, want empty", got) } } func TestGetClaimFloat64(t *testing.T) { claims := map[string]interface{}{ "exp": float64(1719999999), "user_id": "alice", } if got := GetClaimFloat64(claims, "exp"); got != 1719999999 { t.Errorf("GetClaimFloat64(exp) = %v, want %v", got, 1719999999) } if got := GetClaimFloat64(claims, "user_id"); got != 0 { t.Errorf("GetClaimFloat64(user_id) = %v, want 0 (type mismatch)", got) } if got := GetClaimFloat64(nil, "exp"); got != 0 { t.Errorf("GetClaimFloat64(nil) = %v, want 0", got) } } ================================================ FILE: go/encoding/protojson/decode.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 protojson import ( "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) type Unmarshaler struct { // UnmarshalOptions is a configurable JSON format parser. protojson.UnmarshalOptions } func Unmarshal(data []byte, pb proto.Message, options ...UnmarshalerOption) error { m := Unmarshaler{ UnmarshalOptions: protojson.UnmarshalOptions{ AllowPartial: true, DiscardUnknown: true, }, } m.ApplyOptions(options...) return m.Unmarshal(data, pb) } ================================================ FILE: go/encoding/protojson/decode.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 protojson // If AllowPartial is set, input for messages that will result in missing func WithUnMashalAllowPartial(allowPartial bool) UnmarshalerOption { return UnmarshalerOptionFunc(func(m *Unmarshaler) { m.AllowPartial = allowPartial }) } // If DiscardUnknown is set, unknown fields are ignored. func WithUnmashalDiscardUnknown(discardUnknown bool) UnmarshalerOption { return UnmarshalerOptionFunc(func(m *Unmarshaler) { m.DiscardUnknown = discardUnknown }) } ================================================ FILE: go/encoding/protojson/decode_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 protojson // A UnmarshalerOption sets options. type UnmarshalerOption interface { apply(*Unmarshaler) } // EmptyUnmarshalerOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyUnmarshalerOption struct{} func (EmptyUnmarshalerOption) apply(*Unmarshaler) {} // UnmarshalerOptionFunc wraps a function that modifies Client into an // implementation of the UnmarshalerOption interface. type UnmarshalerOptionFunc func(*Unmarshaler) func (f UnmarshalerOptionFunc) apply(do *Unmarshaler) { f(do) } // sample code for option, default for nothing to change func _UnmarshalerOptionWithDefault() UnmarshalerOption { return UnmarshalerOptionFunc(func(*Unmarshaler) { // nothing to change }) } func (o *Unmarshaler) ApplyOptions(options ...UnmarshalerOption) *Unmarshaler { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/encoding/protojson/encode.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 protojson import ( "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) type Marshaler struct { // MarshalOptions is a configurable JSON format marshaler. protojson.MarshalOptions } func Marshal(pb proto.Message, options ...MarshalerOption) ([]byte, error) { m := Marshaler{ MarshalOptions: protojson.MarshalOptions{ AllowPartial: true, }, } m.ApplyOptions(options...) return m.Marshal(pb) } ================================================ FILE: go/encoding/protojson/encode.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 protojson func WithMashalMultiline(multiline bool) MarshalerOption { return MarshalerOptionFunc(func(m *Marshaler) { m.Multiline = multiline }) } func WithMashalUseProtoNames(useProtoNames bool) MarshalerOption { return MarshalerOptionFunc(func(m *Marshaler) { m.UseProtoNames = useProtoNames }) } func WithMashalUseEnumNumbers(useEnumNumbers bool) MarshalerOption { return MarshalerOptionFunc(func(m *Marshaler) { m.UseEnumNumbers = useEnumNumbers }) } func WithMashalEmitUnpopulated(emitUnpopulated bool) MarshalerOption { return MarshalerOptionFunc(func(m *Marshaler) { m.EmitUnpopulated = emitUnpopulated }) } ================================================ FILE: go/encoding/protojson/encode_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 protojson // A MarshalerOption sets options. type MarshalerOption interface { apply(*Marshaler) } // EmptyMarshalerOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyMarshalerOption struct{} func (EmptyMarshalerOption) apply(*Marshaler) {} // MarshalerOptionFunc wraps a function that modifies Client into an // implementation of the MarshalerOption interface. type MarshalerOptionFunc func(*Marshaler) func (f MarshalerOptionFunc) apply(do *Marshaler) { f(do) } // sample code for option, default for nothing to change func _MarshalerOptionWithDefault() MarshalerOption { return MarshalerOptionFunc(func(*Marshaler) { // nothing to change }) } func (o *Marshaler) ApplyOptions(options ...MarshalerOption) *Marshaler { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/encoding/protojson/protojson_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 protojson_test import ( "testing" "github.com/google/uuid" protojson_ "github.com/kaydxh/golang/go/encoding/protojson" testdata_ "github.com/kaydxh/golang/go/encoding/protojson/testdata" ) func TestMarshal(t *testing.T) { request := &testdata_.DateRequest{ RequestId: uuid.New().String(), } data, err := protojson_.Marshal(request) if err != nil { t.Fatalf("failed to marshal, err: %v", err) } t.Logf("marshal data: %v", string(data)) var req testdata_.DateRequest err = protojson_.Unmarshal(data, &req) if err != nil { t.Fatalf("failed to unmarshal, err: %v", err) } t.Logf("unmarshal object: %v", req.String()) } ================================================ FILE: go/encoding/protojson/testdata/date.pb.go ================================================ /* *Copyright (c) 2022, kaydxh * *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. */ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 // protoc v3.13.0 // source: go/encoding/protojson/testdata/date.proto package date import ( _ "github.com/golang/protobuf/protoc-gen-go/descriptor" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type DateRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RequestId string `protobuf:"bytes,1,opt,name=request_id,json=RequestId,proto3" json:"request_id,omitempty"` } func (x *DateRequest) Reset() { *x = DateRequest{} if protoimpl.UnsafeEnabled { mi := &file_go_encoding_protojson_testdata_date_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DateRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*DateRequest) ProtoMessage() {} func (x *DateRequest) ProtoReflect() protoreflect.Message { mi := &file_go_encoding_protojson_testdata_date_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DateRequest.ProtoReflect.Descriptor instead. func (*DateRequest) Descriptor() ([]byte, []int) { return file_go_encoding_protojson_testdata_date_proto_rawDescGZIP(), []int{0} } func (x *DateRequest) GetRequestId() string { if x != nil { return x.RequestId } return "" } type DateResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RequestId string `protobuf:"bytes,1,opt,name=request_id,json=RequestId,proto3" json:"request_id,omitempty"` Date string `protobuf:"bytes,2,opt,name=date,json=Date,proto3" json:"date,omitempty"` } func (x *DateResponse) Reset() { *x = DateResponse{} if protoimpl.UnsafeEnabled { mi := &file_go_encoding_protojson_testdata_date_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DateResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*DateResponse) ProtoMessage() {} func (x *DateResponse) ProtoReflect() protoreflect.Message { mi := &file_go_encoding_protojson_testdata_date_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DateResponse.ProtoReflect.Descriptor instead. func (*DateResponse) Descriptor() ([]byte, []int) { return file_go_encoding_protojson_testdata_date_proto_rawDescGZIP(), []int{1} } func (x *DateResponse) GetRequestId() string { if x != nil { return x.RequestId } return "" } func (x *DateResponse) GetDate() string { if x != nil { return x.Date } return "" } var File_go_encoding_protojson_testdata_date_proto protoreflect.FileDescriptor var file_go_encoding_protojson_testdata_date_proto_rawDesc = []byte{ 0x0a, 0x29, 0x67, 0x6f, 0x2f, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x6a, 0x73, 0x6f, 0x6e, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x64, 0x61, 0x74, 0x61, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1a, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x67, 0x6f, 0x2e, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2c, 0x0a, 0x0b, 0x44, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0x41, 0x0a, 0x0c, 0x44, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x44, 0x61, 0x74, 0x65, 0x42, 0x2e, 0x5a, 0x2c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x67, 0x6f, 0x2f, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x31, 0x3b, 0x64, 0x61, 0x74, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_go_encoding_protojson_testdata_date_proto_rawDescOnce sync.Once file_go_encoding_protojson_testdata_date_proto_rawDescData = file_go_encoding_protojson_testdata_date_proto_rawDesc ) func file_go_encoding_protojson_testdata_date_proto_rawDescGZIP() []byte { file_go_encoding_protojson_testdata_date_proto_rawDescOnce.Do(func() { file_go_encoding_protojson_testdata_date_proto_rawDescData = protoimpl.X.CompressGZIP(file_go_encoding_protojson_testdata_date_proto_rawDescData) }) return file_go_encoding_protojson_testdata_date_proto_rawDescData } var file_go_encoding_protojson_testdata_date_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_go_encoding_protojson_testdata_date_proto_goTypes = []interface{}{ (*DateRequest)(nil), // 0: golang.go.encoding.date.v1.DateRequest (*DateResponse)(nil), // 1: golang.go.encoding.date.v1.DateResponse } var file_go_encoding_protojson_testdata_date_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_go_encoding_protojson_testdata_date_proto_init() } func file_go_encoding_protojson_testdata_date_proto_init() { if File_go_encoding_protojson_testdata_date_proto != nil { return } if !protoimpl.UnsafeEnabled { file_go_encoding_protojson_testdata_date_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DateRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_go_encoding_protojson_testdata_date_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DateResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_go_encoding_protojson_testdata_date_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_go_encoding_protojson_testdata_date_proto_goTypes, DependencyIndexes: file_go_encoding_protojson_testdata_date_proto_depIdxs, MessageInfos: file_go_encoding_protojson_testdata_date_proto_msgTypes, }.Build() File_go_encoding_protojson_testdata_date_proto = out.File file_go_encoding_protojson_testdata_date_proto_rawDesc = nil file_go_encoding_protojson_testdata_date_proto_goTypes = nil file_go_encoding_protojson_testdata_date_proto_depIdxs = nil } ================================================ FILE: go/encoding/protojson/testdata/date.proto ================================================ syntax = "proto3"; package golang.go.encoding.date.v1; import "google/protobuf/descriptor.proto"; option go_package = "github.com/kaydxh/golang/go/encoding/v1;date"; message DateRequest { string request_id = 1[json_name = "RequestId"]; } message DateResponse { string request_id = 1 [json_name = "RequestId"]; string date = 2 [json_name = "Date"]; } ================================================ FILE: go/errors/error.code.go ================================================ package errors import "errors" var ( ErrNotEnabled = errors.New("not enabled") ) ================================================ FILE: go/errors/error.grpc.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 errors import ( "errors" "fmt" "strconv" "strings" "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func FromError(err error) (s *status.Status, ok bool) { s, ok = status.FromError(err) if ok { return s, ok } var gRPCStatus interface { GRPCStatus() *status.Status } if errors.As(err, &gRPCStatus) { s = gRPCStatus.GRPCStatus() //ok = true ok = s != nil } return s, ok } func ErrorToCodeString(err error) string { if err == nil { return codes.OK.String() } s, ok := FromError(err) if !ok { return err.Error() } codeString := s.Code().String() for _, detail := range s.Details() { switch detail := detail.(type) { case *errdetails.ErrorInfo: if detail.GetReason() != "" { codeString = detail.GetReason() } } } return codeString } // Error Message func ErrorToString(err error) string { if err == nil { return codes.OK.String() } s, ok := FromError(err) if !ok { return err.Error() } return s.Message() } func ErrorToCode(err error) codes.Code { if err == nil { return codes.OK } s, ok := FromError(err) if !ok { return codes.Unknown } return s.Code() } func Errorf(code interface{}, format string, a ...interface{}) error { c, ok := code.(codes.Code) if !ok { c = codes.Unknown num, err := strconv.Atoi(fmt.Sprintf("%d", code)) if err == nil { c = codes.Code(num) } } if c == codes.OK { return nil } var message string codeStringer, ok := code.(fmt.Stringer) if ok { message = strings.ReplaceAll(codeStringer.String(), "__", ".") } else { message = c.String() } s := status.New(c, fmt.Sprintf(format, a...)) if s.Code() != codes.OK && message != "" { detail, err := s.WithDetails(&errdetails.ErrorInfo{ Reason: message, }) if err == nil { // replace new status with reason s = detail } } return s.Err() } func Errore(errlist ...error) error { return NewAggregate(errlist) } ================================================ FILE: go/errors/errors.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 errors import ( "errors" ) type Aggregate interface { error Errors() []error Is(error) bool } // NewAggregate converts a slice of errors into an Aggregate interface, which // is itself an implementation of the error interface. If the slice is empty, // this returns nil. // It will check if any of the element of input error list is nil, to avoid // nil pointer panic when call Error(). func NewAggregate(errlist []error) Aggregate { if len(errlist) == 0 { return nil } // In case of input error list contains nil var errs []error for _, e := range errlist { if e != nil { errs = append(errs, e) } } if len(errs) == 0 { return nil } return aggregate(errs) } // This helper implements the error and Errors interfaces. Keeping it private // prevents people from making an aggregate of 0 errors, which is not // an error, but does satisfy the error interface. type aggregate []error // Error is part of the error interface. func (agg aggregate) Error() string { if len(agg) == 0 { // This should never happen, really. return "" } if len(agg) == 1 { return agg[0].Error() } result := "" agg.visit(func(err error) bool { msg := err.Error() if len(result) > 0 { result += ", " } result += msg return false }) return "[" + result + "]" } func (agg aggregate) Is(target error) bool { return agg.visit(func(err error) bool { return errors.Is(err, target) }) } func (agg aggregate) visit(f func(err error) bool) bool { for _, err := range agg { switch err := err.(type) { case aggregate: if match := err.visit(f); match { return match } case Aggregate: for _, nestedErr := range err.Errors() { if match := f(nestedErr); match { return match } } default: if match := f(err); match { return match } } } return false } // Errors is part of the Aggregate interface. func (agg aggregate) Errors() []error { return []error(agg) } ================================================ FILE: go/errors/errors_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 errors_test import ( "errors" "fmt" "testing" errors_ "github.com/kaydxh/golang/go/errors" ) func TestError(t *testing.T) { var errs = []error{fmt.Errorf("error 1"), fmt.Errorf("error 2")} var err error //Aggregate implemnet interface error Error() string err = errors_.NewAggregate(errs) //multiErrorStrings := err errors_.NewAggregate(errs).Errors() multiErrorStrings := err.Error() t.Logf("multiErrorStrings: %v", multiErrorStrings) } func TestErrorIs(t *testing.T) { var ErrInternal = errors.New("internal error") testCases := []struct { err1 error err2 error expected bool }{ { err1: ErrInternal, err2: ErrInternal, expected: true, }, { // the same error messge is not mean the same error err1: errors.New("internal error"), err2: errors.New("internal error"), expected: false, }, { err1: errors.New("internal error1"), err2: errors.New("internal error2"), expected: false, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { err := errors_.NewAggregate([]error{testCase.err1}) if err.Is(testCase.err2) != testCase.expected { t.Fatalf("err[%v] is not expected err2[%v]", err, testCase.err2) } }) } } func TestErrore(t *testing.T) { var ErrInternal = errors.New("FailedOperation__Internal") testCases := []struct { err error code int32 expected bool }{ { err: ErrInternal, code: 100, expected: true, }, { err: errors_.Errore(fmt.Errorf("failed to process,%d", 2), ErrInternal), code: 100, expected: true, }, { err: fmt.Errorf("failed to process, %v", 2), code: 100, expected: false, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { //err := errors_.Errore(testCase.code, testCase.err) err := errors_.Errore(testCase.err) if errors.Is(err, ErrInternal) != testCase.expected { t.Fatalf("err[%v], epected[%v] test err[%v]", err, testCase.expected, testCase.err) } t.Logf("err[%v] expected[%v] test err[%v] ", err, testCase.expected, testCase.err) }) } } ================================================ FILE: go/errors/handler.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 errors import ( "context" "time" "golang.org/x/time/rate" ) // ErrorHandlers is a list of functions which will be invoked when a nonreturnable // error occurs. // should be packaged up into a testable and reusable object. var ErrorHandlers = []func(error){ func() func(err error) { limiter := rate.NewLimiter(rate.Every(time.Millisecond), 1) return func(err error) { // 1ms was the number folks were able to stomach as a global rate limit. // If you need to log errors more than 1000 times a second you // should probably consider fixing your code instead. :) _ = limiter.Wait(context.Background()) } }(), } // HandlerError is a method to invoke when a non-user facing piece of code cannot // return an error and needs to indicate it has been ignored. Invoking this method // is preferable to logging the error - the default behavior is to log but the // errors may be sent to a remote server for analysis. func HandleError(err error) { // this is sometimes called with a nil error. We probably shouldn't fail and should do nothing instead if err == nil { return } for _, fn := range ErrorHandlers { fn(err) } } func ErrorChain(handlers ...func(err error, handled bool) (error, bool)) func(err error, handled bool) error { return func(err error, handled bool) error { for _, h := range handlers { if h != nil { err, handled = h(err, handled) } } return err } } ================================================ FILE: go/filesystem/filesystem.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filesystem import ( "os" "path/filepath" "time" ) // Filesystem is an interface that we can use to mock various filesystem operations type Filesystem interface { // from "os" Stat(name string) (os.FileInfo, error) Create(name string) (File, error) Rename(oldpath, newpath string) error MkdirAll(path string, perm os.FileMode) error Chtimes(name string, atime time.Time, mtime time.Time) error RemoveAll(path string) error Remove(name string) error // from "io/ioutil" ReadFile(filename string) ([]byte, error) TempDir(dir, prefix string) (string, error) TempFile(dir, prefix string) (File, error) ReadDir(dirname string) ([]os.FileInfo, error) Walk(root string, walkFn filepath.WalkFunc) error } // File is an interface that we can use to mock various filesystem operations typically // accessed through the File object from the "os" package type File interface { // for now, the only os.File methods used are those below, add more as necessary Name() string Write(b []byte) (n int, err error) Sync() error Close() error } ================================================ FILE: go/filesystem/mountpoint.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filesystem import ( "bufio" "fmt" "io" "os" "path/filepath" "strconv" "strings" "sync" os_ "github.com/kaydxh/golang/go/os" filepath_ "github.com/kaydxh/golang/go/path/filepath" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) var ( mountsByDevice map[DeviceNumber]*Mount mountsByPath map[string]*Mount mountMutex sync.Mutex mountsInitialized bool allMountsByDevice map[DeviceNumber][]*Mount ) type DeviceNumber uint64 func (num DeviceNumber) String() string { return fmt.Sprintf("%d:%d", unix.Major(uint64(num)), unix.Minor(uint64(num))) } // getNumberOfContainingDevice returns the device number of the filesystem which // contains the given file. If the file is a symlink, it is not dereferenced. func getNumberOfContainingDevice(path string) (DeviceNumber, error) { var stat unix.Stat_t if err := unix.Lstat(path, &stat); err != nil { return 0, err } return DeviceNumber(stat.Dev), nil } func filesystemLacksMainMountError(deviceNumber DeviceNumber) error { return errors.Errorf( "Device %q (%v) lacks a \"main\" mountpoint in the current mount namespace, so it's ambiguous where to store the fscrypt metadata.", getDeviceName(deviceNumber), deviceNumber, ) } type Mount struct { Path string FilesystemType string Device string DeviceNumber DeviceNumber Subtree string ReadOnly bool } func FindMount(path string) (*Mount, error) { mountMutex.Lock() defer mountMutex.Unlock() if err := loadMountInfo(); err != nil { return nil, err } // First try to find the mount by the number of the containing device. deviceNumber, err := getNumberOfContainingDevice(path) if err != nil { return nil, err } mnt, ok := mountsByDevice[deviceNumber] if ok { if mnt == nil { mnts, ok := allMountsByDevice[deviceNumber] if ok { if len(mnts) == 0 { return nil, filesystemLacksMainMountError(deviceNumber) } for _, mnt := range mnts { if strings.HasPrefix(path, mnt.Path) { return mnt, nil } } } return nil, filesystemLacksMainMountError(deviceNumber) } return mnt, nil } // The mount couldn't be found by the number of the containing device. // Fall back to walking up the directory hierarchy and checking for a // mount at each directory path. This is necessary for btrfs, where // files report a different st_dev from the /proc/self/mountinfo entry. curPath, err := filepath_.CanonicalizePath(path) if err != nil { return nil, err } for { mnt := mountsByPath[curPath] if mnt != nil { return mnt, nil } // Move to the parent directory unless we have reached the root. parent := filepath.Dir(curPath) if parent == curPath { return nil, errors.Errorf("couldn't find mountpoint containing %q", path) } curPath = parent } } // loadMountInfo populates the Mount mappings by parsing /proc/self/mountinfo. // It returns an error if the Mount mappings cannot be populated. func loadMountInfo() error { if !mountsInitialized { file, err := os.Open("/proc/self/mountinfo") if err != nil { return err } defer file.Close() if err := readMountInfo(file); err != nil { return err } mountsInitialized = true } return nil } // This is separate from loadMountInfo() only for unit testing. func readMountInfo(r io.Reader) error { mountsByDevice = make(map[DeviceNumber]*Mount) mountsByPath = make(map[string]*Mount) allMountsByDevice = make(map[DeviceNumber][]*Mount) allMountsByPath := make(map[string]*Mount) scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Text() mnt := parseMountInfoLine(line) if mnt == nil { logrus.Warnf("ignoring invalid mountinfo line %q", line) continue } // We can only use mountpoints that are directories for fscrypt. isDir, err := os_.IsDir(mnt.Path) if err != nil { logrus.Errorf("ignoring mountpoint %v because isDir failed", err) continue } if !isDir { logrus.Infof("ignoring mountpoint %q because it is not a directory", mnt.Path) continue } // Note this overrides the info if we have seen the mountpoint // earlier in the file. This is correct behavior because the // mountpoints are listed in mount order. allMountsByPath[mnt.Path] = mnt } // For each filesystem, choose a "main" Mount and discard any additional // bind mounts. fscrypt only cares about the main Mount, since it's // where the fscrypt metadata is stored. Store all the main Mounts in // mountsByDevice and mountsByPath so that they can be found later. for _, mnt := range allMountsByPath { allMountsByDevice[mnt.DeviceNumber] = append(allMountsByDevice[mnt.DeviceNumber], mnt) } for deviceNumber, filesystemMounts := range allMountsByDevice { mnt := findMainMount(filesystemMounts) mountsByDevice[deviceNumber] = mnt // may store an explicit nil entry if mnt != nil { mountsByPath[mnt.Path] = mnt } } return nil } // For more details, see https://www.kernel.org/doc/Documentation/filesystems/proc.txt func parseMountInfoLine(line string) *Mount { fields := strings.Split(line, " ") if len(fields) < 10 { return nil } // Count the optional fields. In case new fields are appended later, // don't simply assume that n == len(fields) - 4. n := 6 for fields[n] != "-" { n++ if n >= len(fields) { return nil } } if n+3 >= len(fields) { return nil } var mnt *Mount = &Mount{} var err error mnt.DeviceNumber, err = newDeviceNumberFromString(fields[2]) if err != nil { return nil } mnt.Subtree = unescapeString(fields[3]) mnt.Path = unescapeString(fields[4]) for _, opt := range strings.Split(fields[5], ",") { if opt == "ro" { mnt.ReadOnly = true } } mnt.FilesystemType = unescapeString(fields[n+1]) mnt.Device = getDeviceName(mnt.DeviceNumber) return mnt } func newDeviceNumberFromString(str string) (DeviceNumber, error) { var major, minor uint32 if count, _ := fmt.Sscanf(str, "%d:%d", &major, &minor); count != 2 { return 0, errors.Errorf("invalid device number string %q", str) } return DeviceNumber(unix.Mkdev(major, minor)), nil } // Unescape octal-encoded escape sequences in a string from the mountinfo file. // The kernel encodes the ' ', '\t', '\n', and '\\' bytes this way. This // function exactly inverts what the kernel does, including by preserving // invalid UTF-8. func unescapeString(str string) string { var sb strings.Builder for i := 0; i < len(str); i++ { b := str[i] if b == '\\' && i+3 < len(str) { if parsed, err := strconv.ParseInt(str[i+1:i+4], 8, 8); err == nil { b = uint8(parsed) i += 3 } } sb.WriteByte(b) } return sb.String() } // We get the device name via the device number rather than use the mount source // field directly. This is necessary to handle a rootfs that was mounted via // the kernel command line, since mountinfo always shows /dev/root for that. // This assumes that the device nodes are in the standard location. func getDeviceName(num DeviceNumber) string { linkPath := fmt.Sprintf("/sys/dev/block/%v", num) if target, err := os.Readlink(linkPath); err == nil { return fmt.Sprintf("/dev/%s", filepath.Base(target)) } return "" } type mountpointTreeNode struct { mount *Mount parent *mountpointTreeNode children []*mountpointTreeNode } func addUncontainedSubtreesRecursive(dst map[string]bool, node *mountpointTreeNode, allUncontainedSubtrees map[string]bool) { if allUncontainedSubtrees[node.mount.Subtree] { dst[node.mount.Subtree] = true } for _, child := range node.children { addUncontainedSubtreesRecursive(dst, child, allUncontainedSubtrees) } } func findMainMount(filesystemMounts []*Mount) *Mount { // Index this filesystem's mounts by path. Note: paths are unique here, // since non-last mounts were already excluded earlier. // // Also build the set of all mounted subtrees. filesystemMountsByPath := make(map[string]*mountpointTreeNode) allSubtrees := make(map[string]bool) for _, mnt := range filesystemMounts { filesystemMountsByPath[mnt.Path] = &mountpointTreeNode{mount: mnt} allSubtrees[mnt.Subtree] = true } // Divide the mounts into non-overlapping trees of mountpoints. for path, mntNode := range filesystemMountsByPath { for path != "/" && mntNode.parent == nil { path = filepath.Dir(path) if parent := filesystemMountsByPath[path]; parent != nil { mntNode.parent = parent parent.children = append(parent.children, mntNode) } } } // Build the set of mounted subtrees that aren't contained in any other // mounted subtree. allUncontainedSubtrees := make(map[string]bool) for subtree := range allSubtrees { contained := false for t := subtree; t != "/" && !contained; { t = filepath.Dir(t) contained = allSubtrees[t] } if !contained { allUncontainedSubtrees[subtree] = true } } // Select the root of a mountpoint tree whose mounted subtrees contain // *all* mounted subtrees. Equivalently, select a mountpoint tree in // which every uncontained subtree is mounted. var mainMount *Mount for _, mntNode := range filesystemMountsByPath { mnt := mntNode.mount if mntNode.parent != nil { continue } uncontainedSubtrees := make(map[string]bool) addUncontainedSubtreesRecursive(uncontainedSubtrees, mntNode, allUncontainedSubtrees) if len(uncontainedSubtrees) != len(allUncontainedSubtrees) { continue } // If there's more than one eligible mount, they should have the // same Subtree. Otherwise it's ambiguous which one to use. if mainMount != nil && mainMount.Subtree != mnt.Subtree { logrus.Errorf( "Unsupported case: %q (%v) has multiple non-overlapping mounts. This filesystem will be ignored!", mnt.Device, mnt.DeviceNumber, ) return nil } // Prefer a read-write mount to a read-only one. if mainMount == nil || mainMount.ReadOnly { mainMount = mnt } } return mainMount } ================================================ FILE: go/flag/flag.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 flag import ( "bytes" "fmt" "io" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" ) const ( usageFmt = "Usage:\n %s\n" ) // NamedFlagSets stores named flag sets in the order of calling FlagSet. type NamedFlagSets struct { // Order is an ordered list of flag set names. Order []string // FlagSets stores the flag sets by name. FlagSets map[string]*pflag.FlagSet // NormalizeNameFunc is the normalize function which used to initialize FlagSets created by NamedFlagSets. NormalizeNameFunc func(f *pflag.FlagSet, name string) pflag.NormalizedName } // FlagSet returns the flag set with the given name and adds it to the // ordered name list if it is not in there yet. func (nfs *NamedFlagSets) FlagSet(name string) *pflag.FlagSet { if nfs.FlagSets == nil { nfs.FlagSets = map[string]*pflag.FlagSet{} } if _, ok := nfs.FlagSets[name]; !ok { flagSet := pflag.NewFlagSet(name, pflag.ExitOnError) flagSet.SetNormalizeFunc(pflag.CommandLine.GetNormalizeFunc()) if nfs.NormalizeNameFunc != nil { flagSet.SetNormalizeFunc(nfs.NormalizeNameFunc) } nfs.FlagSets[name] = flagSet nfs.Order = append(nfs.Order, name) } return nfs.FlagSets[name] } // PrintSections prints the given names flag sets in sections, with the maximal given column number. // If cols is zero, lines are not wrapped. func PrintSections(w io.Writer, fss NamedFlagSets, cols int) { for _, name := range fss.Order { fs := fss.FlagSets[name] if !fs.HasFlags() { continue } wideFS := pflag.NewFlagSet("", pflag.ExitOnError) wideFS.AddFlagSet(fs) var zzz string if cols > 24 { zzz = strings.Repeat("z", cols-24) wideFS.Int(zzz, 0, strings.Repeat("z", cols-24)) } var buf bytes.Buffer fmt.Fprintf(&buf, "\n%s flags:\n\n%s", strings.ToUpper(name[:1])+name[1:], wideFS.FlagUsagesWrapped(cols)) if cols > 24 { i := strings.Index(buf.String(), zzz) lines := strings.Split(buf.String()[:i], "\n") fmt.Fprint(w, strings.Join(lines[:len(lines)-1], "\n")) fmt.Fprintln(w) } else { fmt.Fprint(w, buf.String()) } } } // SetUsageAndHelpFunc set both usage and help function. // Print the flag sets we need instead of all of them. func SetUsageAndHelpFunc(cmd *cobra.Command, fss NamedFlagSets, cols int) { cmd.SetUsageFunc(func(cmd *cobra.Command) error { fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine()) PrintSections(cmd.OutOrStderr(), fss, cols) return nil }) cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) { fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine()) PrintSections(cmd.OutOrStdout(), fss, cols) }) } ================================================ FILE: go/go.mod ================================================ module github.com/kaydxh/golang/go go 1.24.0 require ( github.com/gin-gonic/gin v1.11.0 github.com/go-playground/validator/v10 v10.28.0 github.com/golang/protobuf v1.5.4 github.com/google/uuid v1.6.0 github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 github.com/moby/term v0.5.2 github.com/pkg/errors v0.9.1 github.com/shirou/gopsutil v3.21.11+incompatible github.com/sirupsen/logrus v1.9.3 github.com/spf13/cobra v1.10.1 github.com/spf13/pflag v1.0.10 github.com/stretchr/testify v1.11.1 golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 golang.org/x/net v0.48.0 golang.org/x/sys v0.39.0 golang.org/x/text v0.32.0 golang.org/x/time v0.14.0 google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 google.golang.org/grpc v1.77.0 google.golang.org/protobuf v1.36.10 gotest.tools v2.2.0+incompatible gotest.tools/v3 v3.5.2 ) require ( github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) ================================================ FILE: go/go.sum ================================================ github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s= github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0= golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= ================================================ FILE: go/idgen/id_gen.go ================================================ // Package idgen 提供基于 Snowflake 算法的分布式唯一 ID 生成器 // // ID 结构 (64位): // - 1位: 保留位(始终为0) // - 41位: 时间戳(毫秒级) // - 10位: 机器ID(支持0-1023台机器) // - 12位: 序列号(每毫秒最多4096个ID) // // 使用示例: // // gen := idgen.NewGenerator(1) // 机器ID为1 // id := gen.NextID() // fmt.Printf("生成的ID: %d\n", id) package idgen import ( "encoding/binary" "errors" "fmt" "sync" "time" "github.com/google/uuid" ) const ( // Epoch 是自定义纪元时间戳(毫秒),默认为 2024-01-01 00:00:00 UTC // 可以根据项目实际启动时间调整,以获得更长的使用寿命 Epoch int64 = 1704067200000 // 2024-01-01 00:00:00 UTC // 各部分的位数 workerIDBits = 10 // 机器ID位数 sequenceBits = 12 // 序列号位数 // 最大值 maxWorkerID = -1 ^ (-1 << workerIDBits) // 1023 maxSequence = -1 ^ (-1 << sequenceBits) // 4095 // 位移量 workerIDShift = sequenceBits // 12 timestampShift = sequenceBits + workerIDBits // 22 ) var ( // ErrInvalidWorkerID 当机器ID超出范围时返回 ErrInvalidWorkerID = errors.New("worker ID must be between 0 and 1023") // ErrClockMovedBackwards 当系统时钟回拨时返回 ErrClockMovedBackwards = errors.New("clock moved backwards") ) // Generator 是一个线程安全的 ID 生成器 type Generator struct { mu sync.Mutex workerID int64 sequence int64 lastTimestamp int64 } // NewGenerator 创建一个新的 ID 生成器 // workerID 必须在 0-1023 范围内,用于区分不同的机器或实例 func NewGenerator(workerID int64) (*Generator, error) { if workerID < 0 || workerID > maxWorkerID { return nil, ErrInvalidWorkerID } return &Generator{ workerID: workerID, sequence: 0, lastTimestamp: 0, }, nil } // MustNewGenerator 创建一个新的 ID 生成器,如果出错则 panic // 适用于在初始化阶段使用 func MustNewGenerator(workerID int64) *Generator { gen, err := NewGenerator(workerID) if err != nil { panic(fmt.Sprintf("failed to create generator: %v", err)) } return gen } // NextID 生成下一个唯一 ID // 返回一个 uint64 类型的唯一标识符 func (g *Generator) NextID() (uint64, error) { g.mu.Lock() defer g.mu.Unlock() timestamp := g.currentMillis() // 检测时钟回拨 if timestamp < g.lastTimestamp { return 0, fmt.Errorf("%w: refused to generate id for %d milliseconds", ErrClockMovedBackwards, g.lastTimestamp-timestamp) } // 同一毫秒内 if timestamp == g.lastTimestamp { g.sequence = (g.sequence + 1) & maxSequence if g.sequence == 0 { // 序列号溢出,等待下一毫秒 timestamp = g.waitNextMillis(g.lastTimestamp) } } else { // 新的毫秒,重置序列号 g.sequence = 0 } g.lastTimestamp = timestamp // 组合各部分生成最终 ID id := uint64((timestamp-Epoch)<> workerIDShift) & maxWorkerID timestamp = (int64(id) >> timestampShift) + Epoch return } // GetTimestamp 从 ID 中提取时间戳 func GetTimestamp(id uint64) time.Time { timestamp, _, _ := ParseID(id) return time.UnixMilli(timestamp) } // GetWorkerID 从 ID 中提取机器ID func GetWorkerID(id uint64) int64 { _, workerID, _ := ParseID(id) return workerID } // GetSequence 从 ID 中提取序列号 func GetSequence(id uint64) int64 { _, _, sequence := ParseID(id) return sequence } // GenerateUint64FromUUID 生成uint64 func GenerateUint64FromUUID() uint64 { id := uuid.New() return UUIDToUint64XOR(id) } // UUIDToUint64XOR 将UUID转换为uint64 func UUIDToUint64XOR(id uuid.UUID) uint64 { high := binary.BigEndian.Uint64(id[:8]) low := binary.BigEndian.Uint64(id[8:]) return high ^ low } ================================================ FILE: go/idgen/id_gen_test.go ================================================ package idgen import ( "sync" "testing" "time" ) // TestNewGenerator 测试生成器的创建 func TestNewGenerator(t *testing.T) { tests := []struct { name string workerID int64 wantError bool }{ {"valid worker ID 0", 0, false}, {"valid worker ID 1", 1, false}, {"valid worker ID 512", 512, false}, {"valid worker ID 1023", 1023, false}, {"invalid worker ID -1", -1, true}, {"invalid worker ID 1024", 1024, true}, {"invalid worker ID 2000", 2000, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gen, err := NewGenerator(tt.workerID) if tt.wantError { if err == nil { t.Errorf("NewGenerator(%d) expected error, got nil", tt.workerID) } if gen != nil { t.Errorf("NewGenerator(%d) expected nil generator on error", tt.workerID) } } else { if err != nil { t.Errorf("NewGenerator(%d) unexpected error: %v", tt.workerID, err) } if gen == nil { t.Errorf("NewGenerator(%d) returned nil generator", tt.workerID) } if gen.workerID != tt.workerID { t.Errorf("NewGenerator(%d) workerID = %d, want %d", tt.workerID, gen.workerID, tt.workerID) } } }) } } // TestMustNewGenerator 测试 MustNewGenerator func TestMustNewGenerator(t *testing.T) { // 正常情况 t.Run("valid worker ID", func(t *testing.T) { defer func() { if r := recover(); r != nil { t.Errorf("MustNewGenerator(1) should not panic, got: %v", r) } }() gen := MustNewGenerator(1) if gen == nil { t.Error("MustNewGenerator(1) returned nil") } }) // 应该 panic 的情况 t.Run("invalid worker ID should panic", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("MustNewGenerator(1024) should panic but didn't") } }() MustNewGenerator(1024) }) } // TestNextID 测试基本的ID生成 func TestNextID(t *testing.T) { gen := MustNewGenerator(1) // 生成多个ID,确保都能成功 ids := make([]uint64, 100) for i := 0; i < 100; i++ { id, err := gen.NextID() if err != nil { t.Fatalf("NextID() error: %v", err) } if id == 0 { t.Error("NextID() returned 0") } ids[i] = id } // 检查ID是否递增 for i := 1; i < len(ids); i++ { if ids[i] <= ids[i-1] { t.Errorf("IDs not increasing: ids[%d]=%d, ids[%d]=%d", i-1, ids[i-1], i, ids[i]) } } } // TestMustNextID 测试 MustNextID func TestMustNextID(t *testing.T) { gen := MustNewGenerator(1) defer func() { if r := recover(); r != nil { t.Errorf("MustNextID() should not panic, got: %v", r) } }() id := gen.MustNextID() if id == 0 { t.Error("MustNextID() returned 0") } } // TestIDUniqueness 测试ID的唯一性 func TestIDUniqueness(t *testing.T) { gen := MustNewGenerator(1) count := 10000 ids := make(map[uint64]bool, count) for i := 0; i < count; i++ { id := gen.MustNextID() if ids[id] { t.Fatalf("Duplicate ID found: %d", id) } ids[id] = true } if len(ids) != count { t.Errorf("Expected %d unique IDs, got %d", count, len(ids)) } } // TestWorkerIDInGeneratedID 测试生成的ID中是否包含正确的机器ID func TestWorkerIDInGeneratedID(t *testing.T) { tests := []int64{0, 1, 100, 512, 1023} for _, workerID := range tests { t.Run(formatWorkerID(workerID), func(t *testing.T) { gen := MustNewGenerator(workerID) id := gen.MustNextID() extractedWorkerID := GetWorkerID(id) if extractedWorkerID != workerID { t.Errorf("WorkerID mismatch: generated with %d, extracted %d", workerID, extractedWorkerID) } }) } } // TestParseID 测试ID解析功能 func TestParseID(t *testing.T) { workerID := int64(123) gen := MustNewGenerator(workerID) beforeTime := time.Now() id := gen.MustNextID() afterTime := time.Now() timestamp, parsedWorkerID, sequence := ParseID(id) // 检查时间戳是否在合理范围内 if timestamp < beforeTime.UnixMilli() || timestamp > afterTime.UnixMilli() { t.Errorf("Timestamp out of range: %d not between %d and %d", timestamp, beforeTime.UnixMilli(), afterTime.UnixMilli()) } // 检查机器ID if parsedWorkerID != workerID { t.Errorf("WorkerID mismatch: expected %d, got %d", workerID, parsedWorkerID) } // 检查序列号 if sequence < 0 || sequence > maxSequence { t.Errorf("Sequence out of range: %d", sequence) } } // TestGetTimestamp 测试时间戳提取 func TestGetTimestamp(t *testing.T) { gen := MustNewGenerator(1) before := time.Now() time.Sleep(10 * time.Millisecond) id := gen.MustNextID() time.Sleep(10 * time.Millisecond) after := time.Now() timestamp := GetTimestamp(id) if timestamp.Before(before) || timestamp.After(after) { t.Errorf("Timestamp %v not between %v and %v", timestamp, before, after) } } // TestSequenceOverflow 测试同一毫秒内的序列号溢出 func TestSequenceOverflow(t *testing.T) { gen := MustNewGenerator(1) // 快速生成大量ID,可能触发序列号溢出 count := 5000 ids := make([]uint64, count) start := time.Now() for i := 0; i < count; i++ { ids[i] = gen.MustNextID() } elapsed := time.Since(start) t.Logf("Generated %d IDs in %v", count, elapsed) // 检查唯一性 idMap := make(map[uint64]bool) for _, id := range ids { if idMap[id] { t.Fatalf("Duplicate ID found: %d", id) } idMap[id] = true } } // TestConcurrentGeneration 并发测试 func TestConcurrentGeneration(t *testing.T) { gen := MustNewGenerator(1) goroutines := 100 idsPerGoroutine := 1000 totalIDs := goroutines * idsPerGoroutine var wg sync.WaitGroup idChan := make(chan uint64, totalIDs) start := time.Now() // 启动多个goroutine并发生成ID for i := 0; i < goroutines; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < idsPerGoroutine; j++ { id := gen.MustNextID() idChan <- id } }() } // 等待所有goroutine完成 wg.Wait() close(idChan) elapsed := time.Since(start) t.Logf("Generated %d IDs concurrently in %v (%.0f IDs/sec)", totalIDs, elapsed, float64(totalIDs)/elapsed.Seconds()) // 检查唯一性 idMap := make(map[uint64]bool, totalIDs) duplicates := 0 for id := range idChan { if idMap[id] { duplicates++ t.Errorf("Duplicate ID found: %d", id) } idMap[id] = true } if duplicates > 0 { t.Errorf("Found %d duplicate IDs", duplicates) } if len(idMap) != totalIDs { t.Errorf("Expected %d unique IDs, got %d", totalIDs, len(idMap)) } } // TestMultipleGenerators 测试多个生成器同时工作 func TestMultipleGenerators(t *testing.T) { workers := 10 idsPerWorker := 1000 totalIDs := workers * idsPerWorker var wg sync.WaitGroup idChan := make(chan uint64, totalIDs) // 创建多个生成器,每个使用不同的机器ID for workerID := 0; workerID < workers; workerID++ { wg.Add(1) go func(wID int64) { defer wg.Done() gen := MustNewGenerator(wID) for i := 0; i < idsPerWorker; i++ { id := gen.MustNextID() idChan <- id } }(int64(workerID)) } wg.Wait() close(idChan) // 检查所有ID的唯一性 idMap := make(map[uint64]bool, totalIDs) for id := range idChan { if idMap[id] { t.Errorf("Duplicate ID found: %d", id) } idMap[id] = true } if len(idMap) != totalIDs { t.Errorf("Expected %d unique IDs, got %d", totalIDs, len(idMap)) } } // TestConcurrentSameWorker 测试同一个生成器的高并发场景 func TestConcurrentSameWorker(t *testing.T) { gen := MustNewGenerator(1) goroutines := 1000 idsPerGoroutine := 100 totalIDs := goroutines * idsPerGoroutine var wg sync.WaitGroup var mu sync.Mutex idMap := make(map[uint64]bool, totalIDs) duplicates := 0 start := time.Now() for i := 0; i < goroutines; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < idsPerGoroutine; j++ { id := gen.MustNextID() mu.Lock() if idMap[id] { duplicates++ } idMap[id] = true mu.Unlock() } }() } wg.Wait() elapsed := time.Since(start) t.Logf("Generated %d IDs with %d goroutines in %v (%.0f IDs/sec)", totalIDs, goroutines, elapsed, float64(totalIDs)/elapsed.Seconds()) if duplicates > 0 { t.Errorf("Found %d duplicate IDs in concurrent test", duplicates) } if len(idMap) != totalIDs { t.Errorf("Expected %d unique IDs, got %d", totalIDs, len(idMap)) } } // BenchmarkNextID 基准测试:单线程生成性能 func BenchmarkNextID(b *testing.B) { gen := MustNewGenerator(1) b.ResetTimer() for i := 0; i < b.N; i++ { gen.MustNextID() } } // BenchmarkNextIDParallel 基准测试:并发生成性能 func BenchmarkNextIDParallel(b *testing.B) { gen := MustNewGenerator(1) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { gen.MustNextID() } }) } // BenchmarkParseID 基准测试:ID解析性能 func BenchmarkParseID(b *testing.B) { gen := MustNewGenerator(1) id := gen.MustNextID() b.ResetTimer() for i := 0; i < b.N; i++ { ParseID(id) } } // 辅助函数:格式化机器ID用于测试名称 func formatWorkerID(workerID int64) string { return string(rune('0' + workerID%10)) } ================================================ FILE: go/idgen/wk_id_gen.go ================================================ package idgen import ( "crypto/md5" "encoding/binary" "fmt" "net" "os" "strings" ) // WorkerIDGenerator 用于根据机器信息自动生成 WorkerID type WorkerIDGenerator struct{} // NewWorkerIDGenerator 创建一个 WorkerID 生成器 func NewWorkerIDGenerator() *WorkerIDGenerator { return &WorkerIDGenerator{} } // GenerateWorkerID 根据机器信息自动生成 WorkerID (0-1023) // 优先级: 环境变量 > IP地址 > MAC地址 > 主机名 func (w *WorkerIDGenerator) GenerateWorkerID() (int64, error) { // 方法1: 从环境变量读取 if id, ok := w.fromEnv(); ok { return id, nil } // 方法2: 基于IP地址生成 if id, ok := w.fromIP(); ok { return id, nil } // 方法3: 基于MAC地址生成 if id, ok := w.fromMAC(); ok { return id, nil } // 方法4: 基于主机名生成 if id, ok := w.fromHostname(); ok { return id, nil } return 0, fmt.Errorf("failed to generate worker ID from machine info") } // fromEnv 从环境变量读取 WorkerID func (w *WorkerIDGenerator) fromEnv() (int64, bool) { envVars := []string{"WORKER_ID", "MACHINE_ID", "NODE_ID", "POD_ID"} for _, envVar := range envVars { if value := os.Getenv(envVar); value != "" { var id int64 _, err := fmt.Sscanf(value, "%d", &id) if err == nil && id >= 0 && id <= maxWorkerID { return id, true } } } return 0, false } // fromIP 基于本机IP地址生成 WorkerID // 优先使用非回环的IPv4地址 func (w *WorkerIDGenerator) fromIP() (int64, bool) { addrs, err := net.InterfaceAddrs() if err != nil { return 0, false } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipv4 := ipnet.IP.To4(); ipv4 != nil { // 使用IP地址的后两个字节 // 例如: 192.168.1.100 -> (1 << 8) + 100 = 356 id := int64(ipv4[2])<<8 | int64(ipv4[3]) return id & maxWorkerID, true // 确保在0-1023范围内 } } } return 0, false } // fromMAC 基于MAC地址生成 WorkerID func (w *WorkerIDGenerator) fromMAC() (int64, bool) { interfaces, err := net.Interfaces() if err != nil { return 0, false } for _, iface := range interfaces { // 跳过回环接口和没有MAC地址的接口 if iface.Flags&net.FlagLoopback != 0 || len(iface.HardwareAddr) == 0 { continue } // 使用MAC地址的后两个字节 mac := iface.HardwareAddr if len(mac) >= 6 { id := int64(mac[4])<<8 | int64(mac[5]) return id & maxWorkerID, true } } return 0, false } // fromHostname 基于主机名生成 WorkerID func (w *WorkerIDGenerator) fromHostname() (int64, bool) { hostname, err := os.Hostname() if err != nil || hostname == "" { return 0, false } // 使用MD5哈希主机名,取前8字节转换为int64 hash := md5.Sum([]byte(hostname)) id := int64(binary.BigEndian.Uint64(hash[:8])) return (id & maxWorkerID), true } // GetMachineInfo 获取机器信息用于调试 func (w *WorkerIDGenerator) GetMachineInfo() map[string]string { info := make(map[string]string) // 主机名 if hostname, err := os.Hostname(); err == nil { info["hostname"] = hostname } // IP地址 if ips := w.getIPAddresses(); len(ips) > 0 { info["ips"] = strings.Join(ips, ", ") } // MAC地址 if macs := w.getMACAddresses(); len(macs) > 0 { info["macs"] = strings.Join(macs, ", ") } // 环境变量 envVars := []string{"WORKER_ID", "MACHINE_ID", "NODE_ID", "POD_ID"} for _, envVar := range envVars { if value := os.Getenv(envVar); value != "" { info[envVar] = value } } return info } // getIPAddresses 获取所有非回环的IPv4地址 func (w *WorkerIDGenerator) getIPAddresses() []string { var ips []string addrs, err := net.InterfaceAddrs() if err != nil { return ips } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipv4 := ipnet.IP.To4(); ipv4 != nil { ips = append(ips, ipv4.String()) } } } return ips } // getMACAddresses 获取所有网络接口的MAC地址 func (w *WorkerIDGenerator) getMACAddresses() []string { var macs []string interfaces, err := net.Interfaces() if err != nil { return macs } for _, iface := range interfaces { if iface.Flags&net.FlagLoopback == 0 && len(iface.HardwareAddr) > 0 { macs = append(macs, iface.HardwareAddr.String()) } } return macs } // GenerateFromIP 根据指定IP地址生成 WorkerID func GenerateFromIP(ip string) (int64, error) { parsedIP := net.ParseIP(ip) if parsedIP == nil { return 0, fmt.Errorf("invalid IP address: %s", ip) } ipv4 := parsedIP.To4() if ipv4 == nil { return 0, fmt.Errorf("only IPv4 addresses are supported") } // 使用IP的后两个字节 id := int64(ipv4[2])<<8 | int64(ipv4[3]) return id & maxWorkerID, nil } // GenerateFromMAC 根据指定MAC地址生成 WorkerID func GenerateFromMAC(mac string) (int64, error) { hwAddr, err := net.ParseMAC(mac) if err != nil { return 0, fmt.Errorf("invalid MAC address: %s", mac) } if len(hwAddr) < 6 { return 0, fmt.Errorf("MAC address too short") } // 使用MAC地址的后两个字节 id := int64(hwAddr[4])<<8 | int64(hwAddr[5]) return id & maxWorkerID, nil } // GenerateFromString 根据任意字符串生成 WorkerID func GenerateFromString(s string) int64 { hash := md5.Sum([]byte(s)) id := int64(binary.BigEndian.Uint64(hash[:8])) return id & maxWorkerID } // AutoGenerator 自动生成并创建 Generator // 这是一个便捷函数,结合了 WorkerID 生成和 Generator 创建 func AutoGenerator() (*Generator, error) { wg := NewWorkerIDGenerator() workerID, err := wg.GenerateWorkerID() if err != nil { return nil, fmt.Errorf("failed to generate worker ID: %w", err) } gen, err := NewGenerator(workerID) if err != nil { return nil, fmt.Errorf("failed to create generator with worker ID %d: %w", workerID, err) } return gen, nil } // MustAutoGenerator 自动生成并创建 Generator,失败则 panic func MustAutoGenerator() *Generator { gen, err := AutoGenerator() if err != nil { panic(fmt.Sprintf("failed to auto-generate: %v", err)) } return gen } ================================================ FILE: go/idgen/wk_id_gen_test.go ================================================ package idgen import ( "os" "testing" ) // TestGenerateWorkerID 测试自动生成 WorkerID func TestGenerateWorkerID(t *testing.T) { wg := NewWorkerIDGenerator() workerID, err := wg.GenerateWorkerID() if err != nil { t.Fatalf("GenerateWorkerID() error: %v", err) } if workerID < 0 || workerID > maxWorkerID { t.Errorf("WorkerID out of range: %d, expected 0-%d", workerID, maxWorkerID) } t.Logf("Generated WorkerID: %d", workerID) } // TestFromEnv 测试从环境变量生成 func TestFromEnv(t *testing.T) { tests := []struct { name string envVar string envValue string want int64 wantOK bool }{ {"valid WORKER_ID", "WORKER_ID", "42", 42, true}, {"valid MACHINE_ID", "MACHINE_ID", "100", 100, true}, {"valid NODE_ID", "NODE_ID", "1023", 1023, true}, {"invalid value", "WORKER_ID", "abc", 0, false}, {"out of range", "WORKER_ID", "2000", 0, false}, {"negative value", "WORKER_ID", "-1", 0, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // 设置环境变量 os.Setenv(tt.envVar, tt.envValue) defer os.Unsetenv(tt.envVar) wg := NewWorkerIDGenerator() got, ok := wg.fromEnv() if ok != tt.wantOK { t.Errorf("fromEnv() ok = %v, want %v", ok, tt.wantOK) } if ok && got != tt.want { t.Errorf("fromEnv() = %d, want %d", got, tt.want) } }) } } // TestGenerateFromIP 测试从IP生成 func TestGenerateFromIP(t *testing.T) { tests := []struct { name string ip string wantErr bool }{ {"valid IPv4", "192.168.1.100", false}, {"valid IPv4 2", "10.0.0.50", false}, {"valid IPv4 3", "172.16.5.200", false}, {"invalid IP", "256.1.1.1", true}, {"invalid format", "not-an-ip", true}, {"IPv6 not supported", "2001:0db8::1", true}, {"empty string", "", true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { workerID, err := GenerateFromIP(tt.ip) if (err != nil) != tt.wantErr { t.Errorf("GenerateFromIP() error = %v, wantErr %v", err, tt.wantErr) return } if err == nil { if workerID < 0 || workerID > maxWorkerID { t.Errorf("WorkerID out of range: %d", workerID) } t.Logf("IP %s -> WorkerID: %d", tt.ip, workerID) } }) } } // TestGenerateFromMAC 测试从MAC地址生成 func TestGenerateFromMAC(t *testing.T) { tests := []struct { name string mac string wantErr bool }{ {"valid MAC", "00:1A:2B:3C:4D:5E", false}, {"valid MAC 2", "AA:BB:CC:DD:EE:FF", false}, {"valid MAC hyphen", "00-1A-2B-3C-4D-5E", false}, {"invalid MAC", "not-a-mac", true}, {"invalid format", "00:1A:2B:3C", true}, {"empty string", "", true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { workerID, err := GenerateFromMAC(tt.mac) if (err != nil) != tt.wantErr { t.Errorf("GenerateFromMAC() error = %v, wantErr %v", err, tt.wantErr) return } if err == nil { if workerID < 0 || workerID > maxWorkerID { t.Errorf("WorkerID out of range: %d", workerID) } t.Logf("MAC %s -> WorkerID: %d", tt.mac, workerID) } }) } } // TestGenerateFromString 测试从字符串生成 func TestGenerateFromString(t *testing.T) { tests := []string{ "web-server-1", "api-gateway-node-3", "database-replica-5", "my-app-pod-abc123", "", "very-long-string-with-many-characters-to-test-hashing", } for _, s := range tests { t.Run(s, func(t *testing.T) { workerID := GenerateFromString(s) if workerID < 0 || workerID > maxWorkerID { t.Errorf("WorkerID out of range: %d", workerID) } t.Logf("String '%s' -> WorkerID: %d", s, workerID) }) } } // TestGenerateFromStringConsistency 测试字符串生成的一致性 func TestGenerateFromStringConsistency(t *testing.T) { testString := "test-pod-123" // 多次生成应该返回相同的 WorkerID first := GenerateFromString(testString) for i := 0; i < 100; i++ { id := GenerateFromString(testString) if id != first { t.Errorf("Inconsistent WorkerID: first=%d, iteration %d=%d", first, i, id) } } t.Logf("Consistent WorkerID for '%s': %d", testString, first) } // TestGenerateFromStringUniqueness 测试不同字符串生成不同的 WorkerID func TestGenerateFromStringUniqueness(t *testing.T) { strings := []string{ "pod-1", "pod-2", "pod-3", "pod-4", "pod-5", "node-a", "node-b", "node-c", "node-d", "node-e", } seen := make(map[int64]string) collisions := 0 for _, s := range strings { id := GenerateFromString(s) if existing, exists := seen[id]; exists { collisions++ t.Logf("Collision: '%s' and '%s' both generate WorkerID %d", s, existing, id) } else { seen[id] = s } } t.Logf("Generated %d WorkerIDs from %d strings, %d collisions", len(seen), len(strings), collisions) // 碰撞率应该很低(对于10个字符串,期望0-1个碰撞) if collisions > 2 { t.Errorf("Too many collisions: %d", collisions) } } // TestAutoGenerator 测试自动生成器 func TestAutoGenerator(t *testing.T) { gen, err := AutoGenerator() if err != nil { t.Fatalf("AutoGenerator() error: %v", err) } if gen == nil { t.Fatal("AutoGenerator() returned nil") } // 测试生成ID id, err := gen.NextID() if err != nil { t.Errorf("NextID() error: %v", err) } if id == 0 { t.Error("NextID() returned 0") } t.Logf("AutoGenerator created successfully, generated ID: %d", id) } // TestMustAutoGenerator 测试 MustAutoGenerator func TestMustAutoGenerator(t *testing.T) { defer func() { if r := recover(); r != nil { t.Errorf("MustAutoGenerator() should not panic, got: %v", r) } }() gen := MustAutoGenerator() if gen == nil { t.Fatal("MustAutoGenerator() returned nil") } id := gen.MustNextID() if id == 0 { t.Error("MustNextID() returned 0") } t.Logf("MustAutoGenerator created successfully, generated ID: %d", id) } // TestGetMachineInfo 测试获取机器信息 func TestGetMachineInfo(t *testing.T) { wg := NewWorkerIDGenerator() info := wg.GetMachineInfo() if len(info) == 0 { t.Error("GetMachineInfo() returned empty map") } t.Log("Machine Info:") for key, value := range info { t.Logf(" %s: %s", key, value) } } // TestWorkerIDRange 测试所有生成方法都返回有效范围的 WorkerID func TestWorkerIDRange(t *testing.T) { wg := NewWorkerIDGenerator() // 测试自动生成 if id, err := wg.GenerateWorkerID(); err == nil { if id < 0 || id > maxWorkerID { t.Errorf("GenerateWorkerID() = %d, out of range [0, %d]", id, maxWorkerID) } } // 测试从字符串生成 for i := 0; i < 100; i++ { id := GenerateFromString(string(rune(i))) if id < 0 || id > maxWorkerID { t.Errorf("GenerateFromString() = %d, out of range [0, %d]", id, maxWorkerID) } } } // TestEnvironmentPriority 测试环境变量优先级 func TestEnvironmentPriority(t *testing.T) { // 设置环境变量 os.Setenv("WORKER_ID", "999") defer os.Unsetenv("WORKER_ID") wg := NewWorkerIDGenerator() workerID, err := wg.GenerateWorkerID() if err != nil { t.Fatalf("GenerateWorkerID() error: %v", err) } // 应该使用环境变量的值 if workerID != 999 { t.Errorf("Expected WorkerID from env (999), got %d", workerID) } t.Logf("Environment variable correctly prioritized: %d", workerID) } // BenchmarkGenerateWorkerID 基准测试:自动生成 func BenchmarkGenerateWorkerID(b *testing.B) { wg := NewWorkerIDGenerator() b.ResetTimer() for i := 0; i < b.N; i++ { wg.GenerateWorkerID() } } // BenchmarkGenerateFromString 基准测试:从字符串生成 func BenchmarkGenerateFromString(b *testing.B) { testString := "my-pod-name-123" b.ResetTimer() for i := 0; i < b.N; i++ { GenerateFromString(testString) } } // BenchmarkGenerateFromIP 基准测试:从IP生成 func BenchmarkGenerateFromIP(b *testing.B) { testIP := "192.168.1.100" b.ResetTimer() for i := 0; i < b.N; i++ { GenerateFromIP(testIP) } } // BenchmarkAutoGenerator 基准测试:自动生成器 func BenchmarkAutoGenerator(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { AutoGenerator() } } ================================================ FILE: go/io/copy.go ================================================ /* MIT License Copyright (c) 2020 kay 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 io import ( "fmt" "io" "os" "path/filepath" os_ "github.com/kaydxh/golang/go/os" ) // Mode indicates whether to use hardlink or copy content type Mode int const ( // Content creates a new file, and copies the content of the file Content Mode = iota // Hardlink creates a new hardlink to the existing file Hardlink ) func CopyAll(src, dst string) (err error) { isDir, err := os_.IsDir(src) if err != nil { return err } if isDir { return CopyDir(src, dst, Content) } return CopyFile(src, dst) } func CopyDir(srcDir, dstDir string, copyMode Mode) (err error) { return filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error { if err != nil { return err } // Rebase path relPath, err := filepath.Rel(srcDir, srcPath) if err != nil { return err } dstPath := filepath.Join(dstDir, relPath) return CopyPath(srcPath, dstPath, f, copyMode) }) } func CopyRegular(srcPath, dstPath string, fileInfo os.FileInfo) error { srcFile, err := os.Open(srcPath) if err != nil { return err } defer srcFile.Close() // If the destination file already exists, we shouldn't blow it away dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fileInfo.Mode()) if err != nil { return err } defer dstFile.Close() if err = doCopyWithFileClone(srcFile, dstFile); err == nil { return nil } if err = doCopyWithFileRange(srcFile, dstFile, fileInfo); err == nil { return nil } return legacyCopy(srcFile, dstFile) } func legacyCopy(srcFile io.Reader, dstFile io.Writer) error { _, err := io.Copy(dstFile, srcFile) return err } func CopyFile(src, dst string) (err error) { srcAbs, err := filepath.Abs(src) if err != nil { return err } dstAbs, err := filepath.Abs(dst) if err != nil { return err } // open source file sfi, err := os.Stat(srcAbs) if err != nil { return err } if !sfi.Mode().IsRegular() { return fmt.Errorf( "CopyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String(), ) } // open dest file dfi, err := os.Stat(dstAbs) if err != nil { if !os.IsNotExist(err) { return } // file doesn't exist err := os.MkdirAll(filepath.Dir(dst), 0755) if err != nil { return err } } else { if dfi.Mode().IsRegular() { if os.SameFile(sfi, dfi) { return } } else if dfi.Mode().IsDir() { // dst path is exist and dst is dir, so copy file to dst dir // src: src/1.jpg dst: dst/dir/ => dst/dir/1.jpg dst = filepath.Join(dst, filepath.Base(src)) } else { return fmt.Errorf("CopyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String()) } } return copyFileContents(src, dst) } //copyFileContentes copies the contents of the file named src to the file named dst //The destination file will be created if it does not alreay exist. If the destination //file exists, all it's contents will be replaced by the contents of the source file func copyFileContents(src, dst string) (err error) { srcFile, err := os.Open(src) if err != nil { return } defer srcFile.Close() dstFile, err := os.Create(dst) if err != nil { return } defer func() { cerr := dstFile.Close() if err == nil { err = cerr } }() if _, err = io.Copy(dstFile, srcFile); err != nil { return } err = dstFile.Sync() return } ================================================ FILE: go/io/copy_darwin.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 io import "os" func CopyPath(srcPath, dstPath string, f os.FileInfo, copyMode Mode) error { return nil } func doCopyWithFileClone(srcFile, dstFile *os.File) error { return nil } func doCopyWithFileRange(srcFile, dstFile *os.File, fileinfo os.FileInfo) error { return nil } ================================================ FILE: go/io/copy_linux.go ================================================ /* MIT License Copyright (c) 2020 kay 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 io import ( "fmt" "golang.org/x/sys/unix" "os" "syscall" ) func CopyPath(srcPath, dstPath string, f os.FileInfo, copyMode Mode) error { stat, ok := f.Sys().(*syscall.Stat_t) if !ok { return fmt.Errorf("Unable to get raw syscall.Stat_t data for %s", srcPath) } isHardlink := false switch mode := f.Mode(); { case mode.IsRegular(): if copyMode == Hardlink { isHardlink = true if err := os.Link(srcPath, dstPath); err != nil { return err } } else { if err := CopyRegular(srcPath, dstPath, f); err != nil { return err } } case mode.IsDir(): if err := os.Mkdir(dstPath, f.Mode()); err != nil && !os.IsExist(err) { return err } case mode&os.ModeSymlink != 0: link, err := os.Readlink(srcPath) if err != nil { return err } if err := os.Symlink(link, dstPath); err != nil { return err } case mode&os.ModeNamedPipe != 0: fallthrough case mode&os.ModeSocket != 0: if err := unix.Mkfifo(dstPath, uint32(stat.Mode)); err != nil { return err } case mode&os.ModeDevice != 0: if err := unix.Mknod(dstPath, uint32(stat.Mode), int(stat.Rdev)); err != nil { return err } default: return fmt.Errorf("unknown file type (%d / %s) for %s", f.Mode(), f.Mode().String(), srcPath) } // Everything below is copying metadata from src to dst. All this metadata // already shares an inode for hardlinks. if isHardlink { return nil } if err := os.Lchown(dstPath, int(stat.Uid), int(stat.Gid)); err != nil { return err } isSymlink := f.Mode()&os.ModeSymlink != 0 // There is no LChmod, so ignore mode for symlink. Also, this // must happen after chown, as that can modify the file mode if !isSymlink { if err := os.Chmod(dstPath, f.Mode()); err != nil { return err } } return nil } func doCopyWithFileClone(srcFile, dstFile *os.File) error { return unix.IoctlFileClone(int(dstFile.Fd()), int(srcFile.Fd())) } func doCopyWithFileRange(srcFile, dstFile *os.File, fileinfo os.FileInfo) error { amountLeftToCopy := fileinfo.Size() for amountLeftToCopy > 0 { n, err := unix.CopyFileRange(int(srcFile.Fd()), nil, int(dstFile.Fd()), nil, int(amountLeftToCopy), 0) if err != nil { return err } amountLeftToCopy = amountLeftToCopy - int64(n) } return nil } ================================================ FILE: go/io/copy_test.go ================================================ /* MIT License Copyright (c) 2020 kay 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 io_test import ( "bytes" "fmt" "io/ioutil" "math/rand" "os" "path/filepath" "testing" "github.com/kaydxh/golang/go/io" io_ "github.com/kaydxh/golang/go/io" "gotest.tools/v3/assert" ) func TestCopyDir(t *testing.T) { srcDir, err := ioutil.TempDir("", "srcDir") if err != nil { t.Errorf("expect nil, got %v", err) } populateSrcDir(t, srcDir, 3) dstDir, err := ioutil.TempDir("", "dstDir") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(dstDir) err = io.CopyDir(srcDir, dstDir, io.Content) if err != nil { t.Errorf("expect nil, got %v", err) } err = filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error { if err != nil { return err } // Rebase path relPath, err := filepath.Rel(srcDir, srcPath) assert.NilError(t, err) if relPath == "." { return nil } dstPath := filepath.Join(dstDir, relPath) // If we add non-regular dirs and files to the test // then we need to add more checks here. dstFileInfo, err := os.Lstat(dstPath) assert.NilError(t, err) fmt.Println("dstFileInfo: ", dstFileInfo) return nil }) if err != nil { t.Errorf("expect nil, got %v", err) } } func TestCopyFile(t *testing.T) { dir, err := ioutil.TempDir("", "file-copy-check") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(dir) srcFilename := filepath.Join(dir, "srcFilename") dstFilename := filepath.Join(dir, "dstilename") fmt.Println("srcFilename: , dstFilename: ", srcFilename, dstFilename) buf := []byte("hello world") err = ioutil.WriteFile(srcFilename, buf, 0777) if err != nil { t.Errorf("expect nil, got %v", err) } err = io.CopyFile(srcFilename, dstFilename) if err != nil { t.Errorf("expect nil, got %v", err) } readBuf, err := ioutil.ReadFile(srcFilename) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println("srcFilename content: ", string(readBuf)) readBuf, err = ioutil.ReadFile(dstFilename) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println("dstFilename content: ", string(readBuf)) if !bytes.Equal(buf, readBuf) { t.Errorf("expect true, got %v", false) } } func TestCopyAll(t *testing.T) { testCases := []struct { src string dst string }{ { src: "./testdata/file/1.txt", dst: "./testdata.copy/file", }, /* { src: "./testdata/dir", dst: "./testdata.copy/dir", }, */ } for i, testCase := range testCases { t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) { err := io_.CopyAll(testCase.src, testCase.dst) if err != nil { t.Fatalf("copy all expected nil, got %v", err) } }) } } func randomMode(baseMode int) os.FileMode { for i := 0; i < 7; i++ { baseMode = baseMode | (1&rand.Intn(2))< 0 { n, err := file.Seek(offset, io.SeekStart) if err != nil { return err } _, err = file.WriteAt(buf[:nr], n) if err != nil { return err } offset += int64(nr) total += int64(nr) } if err == io.EOF { break } } else { return err } } return nil } ================================================ FILE: go/io/io_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 io_test import ( "bytes" "fmt" "path/filepath" "strings" "sync" "testing" md5_ "github.com/kaydxh/golang/go/crypto/md5" io_ "github.com/kaydxh/golang/go/io" os_ "github.com/kaydxh/golang/go/os" "github.com/stretchr/testify/assert" ) func TestWriteFile(t *testing.T) { testCases := []struct { name string words []byte expected string }{ { name: "./tmp/1.txt", words: []byte("hello world"), expected: "", }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { err := io_.WriteFile(testCase.name, testCase.words, false) if err != nil { t.Fatalf("failed to write file: %v, got : %s", testCase.name, err) } }) } } func TestWriteReadLine(t *testing.T) { testCases := []struct { name string words []string expected string }{ { name: "write no word", words: []string{}, expected: "", }, { name: "write one word", words: []string{"test1"}, expected: "test1\n", }, { name: "write multi words", words: []string{"test1", "test2", "test3"}, expected: "test1 test2 test3\n", }, } testBuffer := bytes.NewBuffer(nil) for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { testBuffer.Reset() io_.WriteLine(testBuffer, testCase.words...) if !strings.EqualFold(testBuffer.String(), testCase.expected) { t.Fatalf( "write word is %v\n expected: %s, got: %s", testCase.words, testCase.expected, testBuffer.String(), ) } }) } lines := io_.ReadLines(testBuffer.Bytes()) assert.Equal(t, "test1 test2 test3", lines[0]) } func TestWriteReadFileLine(t *testing.T) { testCases := []struct { name string words []string expected string }{ { name: "write no word", words: []string{}, expected: "", }, { name: "write one word", words: []string{"test1"}, expected: "test1\n", }, { name: "write multi words", words: []string{"test1", "test2", "test3"}, expected: "test1 test2 test3\n", }, } workDir, _ := os_.Getwd() testFileNew := filepath.Join(workDir, "test-file-new") testFileAppend := filepath.Join(workDir, "test-file-append") for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { err := io_.WriteFileLine(testFileNew, testCase.words, false) assert.Nil(t, err) err = io_.WriteFileLine(testFileAppend, testCase.words, true) assert.Nil(t, err) /* if !strings.EqualFold(testBuffer.String(), testCase.expected) { t.Fatalf( "write word is %v\n expected: %s, got: %s", testCase.words, testCase.expected, testBuffer.String(), ) } */ }) } lines, err := io_.ReadFileLines(testFileAppend) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println("read lines:", lines) } func TestWriteFileLines(t *testing.T) { testCases := []struct { name string words []string expected string }{ { name: "write no word", words: []string{}, expected: "", }, { name: "write one word", words: []string{"test1"}, expected: "test1\n", }, { name: "write multi words", words: []string{"test1", "test2", "test3"}, expected: "test1 test2 test3\n", }, } workDir, _ := os_.Getwd() testFileNew := filepath.Join(workDir, "test-file-new") testFileAppend := filepath.Join(workDir, "test-file-append") for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { err := io_.WriteFileLines(testFileNew, testCase.words, false) assert.Nil(t, err) err = io_.WriteFileLines(testFileAppend, testCase.words, true) assert.Nil(t, err) /* if !strings.EqualFold(testBuffer.String(), testCase.expected) { t.Fatalf( "write word is %v\n expected: %s, got: %s", testCase.words, testCase.expected, testBuffer.String(), ) } */ }) } } func TestWriteAtOneThread(t *testing.T) { testCases := []struct { name string words []byte expected string }{ { name: "write one word", words: []byte("test1"), expected: "test1", }, { name: "write one word", words: []byte("test2"), expected: "test2", }, { name: "write one word", words: []byte("test3"), expected: "test3", }, } var offsets []int64 = []int64{10, 0, 5} workDir, _ := os_.Getwd() testFileOffset := filepath.Join(workDir, "test-file-offset") for i, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { var offset int64 if i > 0 { offset += int64(i * len(testCases[i-1].words)) } fmt.Println("offset: ", offsets[i]) //err := io_.WriteBytesAt(testFileOffset, testCases[i].words, offset) err := io_.WriteBytesAt(testFileOffset, testCases[i].words, offsets[i]) assert.Nil(t, err) }) } } func TestWriteAtMutilThreads(t *testing.T) { testCases := []struct { name string words []byte expected string }{ { name: "write one word", words: []byte("test1"), expected: "test1", }, { name: "write one word", words: []byte("test2"), expected: "test2", }, { name: "write one word", words: []byte("test3"), expected: "test3", }, } workDir, _ := os_.Getwd() testFileOffset := filepath.Join(workDir, "test-file-offset") wg := sync.WaitGroup{} for i, testCase := range testCases { wg.Add(1) go func(name string, index int) { defer wg.Done() t.Run(name, func(t *testing.T) { var offset int64 for j := 0; j < index; j++ { offset += int64(len(testCases[j].words)) } fmt.Printf("write: %s, offset: %d", testCases[index].words, offset) err := io_.WriteBytesAt(testFileOffset, testCases[index].words, offset) assert.Nil(t, err) }) }(testCase.name, i) } wg.Wait() } func TestWriteReaderAtOneThread(t *testing.T) { testCases := []struct { name string words []string expected string }{ { name: "write one word", words: []string{"test1"}, expected: "test1", }, { name: "write one word", words: []string{"test2"}, expected: "test2", }, { name: "write one word", words: []string{"test3"}, expected: "test3", }, } workDir, _ := os_.Getwd() testFile := filepath.Join(workDir, "test-file") for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { err := io_.WriteFileLine(testFile, testCase.words, true) assert.Nil(t, err) }) } file, err := os_.OpenFile(testFile, true) if err != nil { return } defer file.Close() /* fileInfo, err := file.Stat() if err != nil { return } */ testFileCopy := filepath.Join(workDir, "test-file-copy") var offset int64 for _, testCase := range testCases { err = io_.WriteReaderAt(testFileCopy, file, offset, int64(len(testCase.words[0])+1)) offset += int64(len(testCase.words[0]) + 1) assert.Nil(t, err) } sumTestFile, _ := md5_.SumFile(testFile) sumTestFileCopy, _ := md5_.SumFile(testFileCopy) assert.Equal(t, sumTestFile, sumTestFileCopy) } ================================================ FILE: go/io/testdata/dir/file/1.txt ================================================ hello word ================================================ FILE: go/io/testdata/dir/hello.text ================================================ hello word ================================================ FILE: go/io/testdata/file/1.txt ================================================ hello word ================================================ FILE: go/math/exp/exp.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 exp import ( "math" "golang.org/x/exp/constraints" ) const PRECISION = 1e-6 func Max[T constraints.Ordered](s ...T) T { if len(s) == 0 { var zero T return zero } m := s[0] for _, v := range s[1:] { if m < v { m = v } } return m } func Min[T constraints.Ordered](s ...T) T { if len(s) == 0 { var zero T return zero } m := s[0] for _, v := range s[1:] { if m > v { m = v } } return m } func Value[T constraints.Ordered](v, min, max T) T { if v < min { return min } if v > max { return max } return v } func Equal[T float32 | float64](a, b T) bool { return math.Abs(float64(a-b)) < PRECISION } func Sum[T constraints.Ordered](t ...T) T { var sum T for _, v := range t { sum += v } return sum } ================================================ FILE: go/math/exp/exp_test.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 exp_test import ( "fmt" "testing" exp_ "github.com/kaydxh/golang/go/math/exp" ) func TestMax(t *testing.T) { testCases := []struct { v1 int64 v2 int64 expected int64 }{ { v1: 10, v2: 20, expected: 20, }, { v1: 100, v2: 20, expected: 100, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { value := exp_.Max(testCase.v1, testCase.v2) if value != testCase.expected { t.Fatalf("failed to get max for [%v] [%v] got : %v", testCase.v1, testCase.v2, value) } }) } } func TestEqual(t *testing.T) { testCases := []struct { a float32 b float32 expected string }{ { a: 10.1, b: 10.1009, expected: "", }, { a: 10.1, b: 10.100000009, expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%v", i), func(t *testing.T) { equal := exp_.Equal(testCase.a, testCase.b) t.Logf("equal: %v", equal) }) } } ================================================ FILE: go/math/math.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 math import "golang.org/x/exp/constraints" func CountOne[T constraints.Integer](n T) int32 { count := int32(0) for n != 0 { count++ n = n & (n - 1) } return count } ================================================ FILE: go/math/math_test.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 math_test import ( "fmt" "testing" math_ "github.com/kaydxh/golang/go/math" ) func TestCountOne(t *testing.T) { testCases := []struct { value int64 expected string }{ { value: 10, expected: "", }, { value: 2, expected: "", }, { value: 256, expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { n := math_.CountOne(testCase.value) t.Logf("count one %v for %v", n, testCase.value) }) } } ================================================ FILE: go/math/rand/rand.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 rand import ( "fmt" "math/rand" "sync" "time" ) var ( globalRand = rand.New(rand.NewSource(time.Now().UnixNano())) mu sync.Mutex letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") ) // Int implements rand.Int on the global source. func Int() int { mu.Lock() defer mu.Unlock() return globalRand.Int() } // Int31n implements rand.Int31n on the global source. func Int31n(n int32) int32 { mu.Lock() defer mu.Unlock() return globalRand.Int31n(n) } // Uint32 implements rand.Uint32 on the global source. func Uint32() uint32 { mu.Lock() defer mu.Unlock() return globalRand.Uint32() } // Int63n implements rand.Int63n on the global source. func Int63n(n int64) int64 { mu.Lock() defer mu.Unlock() return globalRand.Int63n(n) } // Intn implements rand.Intn on the global source. func Intn(n int) int { mu.Lock() defer mu.Unlock() return globalRand.Intn(n) } // Float32 implements rand.Float32 on the global source. func Float32() float32 { mu.Lock() defer mu.Unlock() return globalRand.Float32() } // Float64 implements rand.Float64 on the global source. func Float64() float64 { mu.Lock() defer mu.Unlock() return globalRand.Float64() } // Uint64 implements rand.Uint64 on the global source. func Uint64() uint64 { mu.Lock() defer mu.Unlock() return globalRand.Uint64() } // Read implements rand.Read on the global source. func Read(p []byte) (n int, err error) { mu.Lock() defer mu.Unlock() return globalRand.Read(p) } // RandInt generate number [min, max). func RangeInt(min, max int) (int, error) { if min < 0 || max < 0 || max <= min { return 0, fmt.Errorf("min or max must > 0 and max > min") } return Intn(max-min) + min, nil } // RangeString generate string length [0, n]. func RangeString(n int) string { b := make([]rune, n) for i := range b { b[i] = letterRunes[rand.Intn(len(letterRunes))] } return string(b) } ================================================ FILE: go/math/rand/rand_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 rand_test import ( "fmt" "math/rand" "strings" "testing" "time" rand_ "github.com/kaydxh/golang/go/math/rand" "github.com/stretchr/testify/assert" ) func TestRand(t *testing.T) { s := fmt.Sprintf("%08v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(100000000)) fmt.Printf("s: %v\n", s) ss := "abc_dvg_123" fmt.Printf("ss %v\n", ss) ts := strings.TrimPrefix(ss, "abc_dvg") fmt.Printf("ts: %v\n", ts) ns := "_abc" nns := strings.Split(ns, "_") fmt.Printf("nns: %v\n", nns) } func TestRangeInt(t *testing.T) { testCases := []struct { min int max int }{ { min: 10, max: 12, }, { min: 10000000, max: 100000000, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("test-%v", i), func(t *testing.T) { r, err := rand_.RangeInt(testCase.min, testCase.max) if err != nil { t.Fatalf("failed to rand int, err: %v", err) } t.Logf("random: %v", r) assert.GreaterOrEqual(t, r, testCase.min) assert.LessOrEqual(t, r, testCase.max) }) } } func TestRead(t *testing.T) { testCases := []struct { p []byte }{ { p: make([]byte, 10), }, { p: make([]byte, 20), }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("test-%v", i), func(t *testing.T) { n, err := rand_.Read(testCase.p) if err != nil { t.Fatalf("failed to rand int, err: %v", err) } t.Logf("read n: %v, p: %v", n, testCase.p) assert.Equal(t, len(testCase.p), n) }) } } func TestRangeString(t *testing.T) { testCases := []struct { n int }{ { n: 0, }, { n: 5, }, { n: 8, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("test-%v", i), func(t *testing.T) { str := rand_.RangeString(testCase.n) t.Logf("str: %v", str) assert.Equal(t, len(str), testCase.n) }) } } ================================================ FILE: go/net/grpc/example/data.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.10 // protoc v5.29.3 // source: go/net/grpc/example/data.proto package v1 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" _ "google.golang.org/protobuf/types/descriptorpb" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type NowRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // proto name 默认为变量名,proto json默认为小驼峰模式, json默认为变量名 // [json_name = "RequestId"]将指定proto json的标签, 此时需要设置 // protojson编解码器选项UseProtoNames为false RequestId string `protobuf:"bytes,1,opt,name=request_id,json=RequestId,proto3" json:"request_id,omitempty"` // 请求ID unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *NowRequest) Reset() { *x = NowRequest{} mi := &file_go_net_grpc_example_data_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *NowRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*NowRequest) ProtoMessage() {} func (x *NowRequest) ProtoReflect() protoreflect.Message { mi := &file_go_net_grpc_example_data_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 NowRequest.ProtoReflect.Descriptor instead. func (*NowRequest) Descriptor() ([]byte, []int) { return file_go_net_grpc_example_data_proto_rawDescGZIP(), []int{0} } func (x *NowRequest) GetRequestId() string { if x != nil { return x.RequestId } return "" } type NowResponse struct { state protoimpl.MessageState `protogen:"open.v1"` RequestId string `protobuf:"bytes,1,opt,name=request_id,json=RequestId,proto3" json:"request_id,omitempty"` // 请求ID Date string `protobuf:"bytes,2,opt,name=date,json=Date,proto3" json:"date,omitempty"` // 当前时间 unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *NowResponse) Reset() { *x = NowResponse{} mi := &file_go_net_grpc_example_data_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *NowResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*NowResponse) ProtoMessage() {} func (x *NowResponse) ProtoReflect() protoreflect.Message { mi := &file_go_net_grpc_example_data_proto_msgTypes[1] 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 NowResponse.ProtoReflect.Descriptor instead. func (*NowResponse) Descriptor() ([]byte, []int) { return file_go_net_grpc_example_data_proto_rawDescGZIP(), []int{1} } func (x *NowResponse) GetRequestId() string { if x != nil { return x.RequestId } return "" } func (x *NowResponse) GetDate() string { if x != nil { return x.Date } return "" } type NowErrorRequest struct { state protoimpl.MessageState `protogen:"open.v1"` RequestId string `protobuf:"bytes,1,opt,name=request_id,json=RequestId,proto3" json:"request_id,omitempty"` // 请求ID unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *NowErrorRequest) Reset() { *x = NowErrorRequest{} mi := &file_go_net_grpc_example_data_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *NowErrorRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*NowErrorRequest) ProtoMessage() {} func (x *NowErrorRequest) ProtoReflect() protoreflect.Message { mi := &file_go_net_grpc_example_data_proto_msgTypes[2] 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 NowErrorRequest.ProtoReflect.Descriptor instead. func (*NowErrorRequest) Descriptor() ([]byte, []int) { return file_go_net_grpc_example_data_proto_rawDescGZIP(), []int{2} } func (x *NowErrorRequest) GetRequestId() string { if x != nil { return x.RequestId } return "" } type NowErrorResponse struct { state protoimpl.MessageState `protogen:"open.v1"` RequestId string `protobuf:"bytes,1,opt,name=request_id,json=RequestId,proto3" json:"request_id,omitempty"` // 请求ID Date string `protobuf:"bytes,2,opt,name=date,json=Date,proto3" json:"date,omitempty"` // 当前时间 unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *NowErrorResponse) Reset() { *x = NowErrorResponse{} mi := &file_go_net_grpc_example_data_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *NowErrorResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*NowErrorResponse) ProtoMessage() {} func (x *NowErrorResponse) ProtoReflect() protoreflect.Message { mi := &file_go_net_grpc_example_data_proto_msgTypes[3] 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 NowErrorResponse.ProtoReflect.Descriptor instead. func (*NowErrorResponse) Descriptor() ([]byte, []int) { return file_go_net_grpc_example_data_proto_rawDescGZIP(), []int{3} } func (x *NowErrorResponse) GetRequestId() string { if x != nil { return x.RequestId } return "" } func (x *NowErrorResponse) GetDate() string { if x != nil { return x.Date } return "" } var File_go_net_grpc_example_data_proto protoreflect.FileDescriptor const file_go_net_grpc_example_data_proto_rawDesc = "" + "\n" + "\x1ego/net/grpc/example/data.proto\x12\x0fsea.api.seadate\x1a google/protobuf/descriptor.proto\"+\n" + "\n" + "NowRequest\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\tR\tRequestId\"@\n" + "\vNowResponse\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\tR\tRequestId\x12\x12\n" + "\x04date\x18\x02 \x01(\tR\x04Date\"0\n" + "\x0fNowErrorRequest\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\tR\tRequestId\"E\n" + "\x10NowErrorResponse\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\tR\tRequestId\x12\x12\n" + "\x04date\x18\x02 \x01(\tR\x04Date2\xa7\x01\n" + "\x0eSeaDateService\x12B\n" + "\x03Now\x12\x1b.sea.api.seadate.NowRequest\x1a\x1c.sea.api.seadate.NowResponse\"\x00\x12Q\n" + "\bNowError\x12 .sea.api.seadate.NowErrorRequest\x1a!.sea.api.seadate.NowErrorResponse\"\x00B7Z5github.com/kaydxh/sea/api/protoapi-spec/seadate/v1;v1b\x06proto3" var ( file_go_net_grpc_example_data_proto_rawDescOnce sync.Once file_go_net_grpc_example_data_proto_rawDescData []byte ) func file_go_net_grpc_example_data_proto_rawDescGZIP() []byte { file_go_net_grpc_example_data_proto_rawDescOnce.Do(func() { file_go_net_grpc_example_data_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_go_net_grpc_example_data_proto_rawDesc), len(file_go_net_grpc_example_data_proto_rawDesc))) }) return file_go_net_grpc_example_data_proto_rawDescData } var file_go_net_grpc_example_data_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_go_net_grpc_example_data_proto_goTypes = []any{ (*NowRequest)(nil), // 0: sea.api.seadate.NowRequest (*NowResponse)(nil), // 1: sea.api.seadate.NowResponse (*NowErrorRequest)(nil), // 2: sea.api.seadate.NowErrorRequest (*NowErrorResponse)(nil), // 3: sea.api.seadate.NowErrorResponse } var file_go_net_grpc_example_data_proto_depIdxs = []int32{ 0, // 0: sea.api.seadate.SeaDateService.Now:input_type -> sea.api.seadate.NowRequest 2, // 1: sea.api.seadate.SeaDateService.NowError:input_type -> sea.api.seadate.NowErrorRequest 1, // 2: sea.api.seadate.SeaDateService.Now:output_type -> sea.api.seadate.NowResponse 3, // 3: sea.api.seadate.SeaDateService.NowError:output_type -> sea.api.seadate.NowErrorResponse 2, // [2:4] is the sub-list for method output_type 0, // [0:2] 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_go_net_grpc_example_data_proto_init() } func file_go_net_grpc_example_data_proto_init() { if File_go_net_grpc_example_data_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_go_net_grpc_example_data_proto_rawDesc), len(file_go_net_grpc_example_data_proto_rawDesc)), NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 1, }, GoTypes: file_go_net_grpc_example_data_proto_goTypes, DependencyIndexes: file_go_net_grpc_example_data_proto_depIdxs, MessageInfos: file_go_net_grpc_example_data_proto_msgTypes, }.Build() File_go_net_grpc_example_data_proto = out.File file_go_net_grpc_example_data_proto_goTypes = nil file_go_net_grpc_example_data_proto_depIdxs = nil } ================================================ FILE: go/net/grpc/example/data.proto ================================================ syntax = "proto3"; package sea.api.seadate; import "google/protobuf/descriptor.proto"; option go_package = "github.com/kaydxh/sea/api/protoapi-spec/seadate/v1;v1"; service SeaDateService { // 生成当前时间 rpc Now(NowRequest) returns (NowResponse) {}; rpc NowError(NowErrorRequest) returns (NowErrorResponse) {}; } message NowRequest { // proto name 默认为变量名,proto json默认为小驼峰模式, json默认为变量名 // [json_name = "RequestId"]将指定proto json的标签, 此时需要设置 // protojson编解码器选项UseProtoNames为false string request_id = 1 [json_name = "RequestId"]; // 请求ID } message NowResponse { string request_id = 1 [json_name = "RequestId"]; // 请求ID string date = 2 [json_name = "Date"]; // 当前时间 } message NowErrorRequest { string request_id = 1 [json_name = "RequestId"]; // 请求ID } message NowErrorResponse { string request_id = 1 [json_name = "RequestId"]; // 请求ID string date = 2 [json_name = "Date"]; // 当前时间 } ================================================ FILE: go/net/grpc/example/data.repository.go ================================================ package v1 import ( "context" grpc_ "github.com/kaydxh/golang/go/net/grpc" ) type Repository struct { grpc_.Repository[SeaDateServiceClient] } func (r *Repository) Now(ctx context.Context, req *NowRequest) (resp *NowResponse, err error) { err = r.Call(ctx, func(ctx context.Context) error { nowResp, err := r.Client.Now(ctx, &NowRequest{}) if err != nil { return err } resp = &NowResponse{ RequestId: req.RequestId, Date: nowResp.GetDate(), } return nil }) return resp, err } ================================================ FILE: go/net/grpc/example/data.repository_test.go ================================================ package v1_test import ( "testing" "time" "context" grpc_ "github.com/kaydxh/golang/go/net/grpc" date_ "github.com/kaydxh/golang/go/net/grpc/example" _ "github.com/kaydxh/golang/go/net/resolver/dns" _ "github.com/kaydxh/golang/go/net/resolver/passthrough" "google.golang.org/grpc" ) func TestNow(t *testing.T) { ctx := context.Background() /* repository, err := grpc_.NewRepository(ctx, grpc_.FactoryConfig[date_.DateServiceClient]{ Addr: "localhost:10001", Timeout: 5 * time.Second, NewServiceClient: func(c *grpc.ClientConn) date_.DateServiceClient { return date_.NewDateServiceClient(c) }, }, ) */ factory, err := grpc_.NewFactory(grpc_.FactoryConfig[date_.SeaDateServiceClient]{ //Addr: "localhost:10001", Addr: "127.0.0.1:10001", Timeout: 5 * time.Second, NewServiceClient: func(c *grpc.ClientConn) date_.SeaDateServiceClient { return date_.NewSeaDateServiceClient(c) }, }, ) if err != nil { t.Errorf("failed to new factory, err: %v", err) } repository, err := factory.NewClient(ctx) if err != nil { t.Errorf("failed to new respository client, err: %v", err) } respWrap := date_.Repository{ Repository: repository, } var resp any err = respWrap.Call(ctx, func(ctx context.Context) error { // short connection newClient, conn, err := respWrap.NewConnect(ctx) if err != nil { return err } defer conn.Close() resp, err = newClient.Now(ctx, &date_.NowRequest{}) //long connection //resp, err = respWrap.Now(ctx, &date_.NowRequest{}) return err }) if err != nil { t.Errorf("failed to call Now, err: %v", err) return } //t.Logf("resp: %v", resp.RequestId) t.Logf("resp: %v", resp) } ================================================ FILE: go/net/grpc/example/data_grpc.pb.go ================================================ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.5.1 // - protoc v5.29.3 // source: go/net/grpc/example/data.proto package v1 import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( SeaDateService_Now_FullMethodName = "/sea.api.seadate.SeaDateService/Now" SeaDateService_NowError_FullMethodName = "/sea.api.seadate.SeaDateService/NowError" ) // SeaDateServiceClient is the client API for SeaDateService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type SeaDateServiceClient interface { // 生成当前时间 Now(ctx context.Context, in *NowRequest, opts ...grpc.CallOption) (*NowResponse, error) NowError(ctx context.Context, in *NowErrorRequest, opts ...grpc.CallOption) (*NowErrorResponse, error) } type seaDateServiceClient struct { cc grpc.ClientConnInterface } func NewSeaDateServiceClient(cc grpc.ClientConnInterface) SeaDateServiceClient { return &seaDateServiceClient{cc} } func (c *seaDateServiceClient) Now(ctx context.Context, in *NowRequest, opts ...grpc.CallOption) (*NowResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(NowResponse) err := c.cc.Invoke(ctx, SeaDateService_Now_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *seaDateServiceClient) NowError(ctx context.Context, in *NowErrorRequest, opts ...grpc.CallOption) (*NowErrorResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(NowErrorResponse) err := c.cc.Invoke(ctx, SeaDateService_NowError_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } // SeaDateServiceServer is the server API for SeaDateService service. // All implementations must embed UnimplementedSeaDateServiceServer // for forward compatibility. type SeaDateServiceServer interface { // 生成当前时间 Now(context.Context, *NowRequest) (*NowResponse, error) NowError(context.Context, *NowErrorRequest) (*NowErrorResponse, error) mustEmbedUnimplementedSeaDateServiceServer() } // UnimplementedSeaDateServiceServer must be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedSeaDateServiceServer struct{} func (UnimplementedSeaDateServiceServer) Now(context.Context, *NowRequest) (*NowResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Now not implemented") } func (UnimplementedSeaDateServiceServer) NowError(context.Context, *NowErrorRequest) (*NowErrorResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method NowError not implemented") } func (UnimplementedSeaDateServiceServer) mustEmbedUnimplementedSeaDateServiceServer() {} func (UnimplementedSeaDateServiceServer) testEmbeddedByValue() {} // UnsafeSeaDateServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to SeaDateServiceServer will // result in compilation errors. type UnsafeSeaDateServiceServer interface { mustEmbedUnimplementedSeaDateServiceServer() } func RegisterSeaDateServiceServer(s grpc.ServiceRegistrar, srv SeaDateServiceServer) { // If the following call pancis, it indicates UnimplementedSeaDateServiceServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&SeaDateService_ServiceDesc, srv) } func _SeaDateService_Now_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(NowRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(SeaDateServiceServer).Now(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: SeaDateService_Now_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SeaDateServiceServer).Now(ctx, req.(*NowRequest)) } return interceptor(ctx, in, info, handler) } func _SeaDateService_NowError_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(NowErrorRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(SeaDateServiceServer).NowError(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: SeaDateService_NowError_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SeaDateServiceServer).NowError(ctx, req.(*NowErrorRequest)) } return interceptor(ctx, in, info, handler) } // SeaDateService_ServiceDesc is the grpc.ServiceDesc for SeaDateService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var SeaDateService_ServiceDesc = grpc.ServiceDesc{ ServiceName: "sea.api.seadate.SeaDateService", HandlerType: (*SeaDateServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Now", Handler: _SeaDateService_Now_Handler, }, { MethodName: "NowError", Handler: _SeaDateService_NowError_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "go/net/grpc/example/data.proto", } ================================================ FILE: go/net/grpc/grpc_client.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 grpc import ( "fmt" "math" "sync" "time" "google.golang.org/grpc" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/keepalive" ) const ( // defaultMaxMsgSize 默认最大消息大小 defaultMaxMsgSize = math.MaxInt32 // 16 * 1024 * 1024 // defaultCallTimeout 默认调用超时时间 defaultCallTimeout = 3 * time.Second // defaultKeepaliveTime 默认 keepalive 时间间隔 defaultKeepaliveTime = 10 * time.Second // defaultKeepaliveTimeout 默认 keepalive 超时时间 defaultKeepaliveTimeout = 3 * time.Second ) // connPoolEntry 连接池条目 type connPoolEntry struct { conn *grpc.ClientConn mu sync.Mutex } var ( // connPool 全局连接池,key 为 address,value 为 *connPoolEntry connPool sync.Map ) // GrpcClient gRPC 客户端封装 type GrpcClient struct { conn *grpc.ClientConn opts grpcClientOptions } // grpcClientOptions gRPC 客户端配置选项 type grpcClientOptions struct { maxMsgSize int // 最大消息大小 disablePrintMethods []string // 禁止打印的方法列表 callTimeout time.Duration // 默认调用超时时间 keepaliveTime time.Duration // keepalive 时间间隔 keepaliveTimeout time.Duration // keepalive 超时时间 unaryInterceptors []grpc.UnaryClientInterceptor // 自定义 Unary 拦截器 streamInterceptors []grpc.StreamClientInterceptor // 自定义 Stream 拦截器 additionalDialOpts []grpc.DialOption // 额外的拨号选项 } // NewGrpcClient 创建一个新的 gRPC 客户端 func NewGrpcClient(addr string, options ...GrpcClientOption) (*GrpcClient, error) { c := &GrpcClient{} c.ApplyOptions(options...) c.setDefaults() dialOpts := c.buildDialOptions() conn, err := grpc.NewClient(addr, dialOpts...) if err != nil { return nil, fmt.Errorf("failed to connect address %s: %w", addr, err) } c.conn = conn return c, nil } // setDefaults 设置默认配置值 func (g *GrpcClient) setDefaults() { if g.opts.maxMsgSize == 0 { g.opts.maxMsgSize = defaultMaxMsgSize } if g.opts.callTimeout == 0 { g.opts.callTimeout = defaultCallTimeout } if g.opts.keepaliveTime == 0 { g.opts.keepaliveTime = defaultKeepaliveTime } if g.opts.keepaliveTimeout == 0 { g.opts.keepaliveTimeout = defaultKeepaliveTimeout } } // buildDialOptions 构建拨号选项 func (g *GrpcClient) buildDialOptions() []grpc.DialOption { return ClientDialOptions( g.opts.maxMsgSize, g.opts.keepaliveTime, g.opts.keepaliveTimeout, g.opts.unaryInterceptors, g.opts.streamInterceptors, g.opts.additionalDialOpts..., ) } // Conn 返回底层的 gRPC 连接 func (g *GrpcClient) Conn() *grpc.ClientConn { return g.conn } // CallTimeout 返回默认的调用超时时间 func (g *GrpcClient) CallTimeout() time.Duration { return g.opts.callTimeout } // Close 关闭 gRPC 连接 func (g *GrpcClient) Close() error { if g.conn == nil { return nil } return g.conn.Close() } // ClientDialOptions 创建 gRPC 拨号选项 func ClientDialOptions( maxMsgSize int, keepaliveTime, keepaliveTimeout time.Duration, unaryInterceptors []grpc.UnaryClientInterceptor, streamInterceptors []grpc.StreamClientInterceptor, additionalOpts ...grpc.DialOption, ) []grpc.DialOption { // 设置默认值 if maxMsgSize == 0 { maxMsgSize = defaultMaxMsgSize } if keepaliveTime == 0 { keepaliveTime = defaultKeepaliveTime } if keepaliveTimeout == 0 { keepaliveTimeout = defaultKeepaliveTimeout } opts := []grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(maxMsgSize), grpc.MaxCallSendMsgSize(maxMsgSize), ), grpc.WithInitialWindowSize(int32(maxMsgSize)), grpc.WithInitialConnWindowSize(int32(maxMsgSize)), grpc.WithStatsHandler(&statHandler{}), grpc.WithKeepaliveParams(keepalive.ClientParameters{ Time: keepaliveTime, Timeout: keepaliveTimeout, PermitWithoutStream: true, }), } // 添加自定义 Unary 拦截器 if len(unaryInterceptors) > 0 { opts = append(opts, grpc.WithChainUnaryInterceptor(unaryInterceptors...)) } // 添加自定义 Stream 拦截器 if len(streamInterceptors) > 0 { opts = append(opts, grpc.WithChainStreamInterceptor(streamInterceptors...)) } // 添加额外的拨号选项 opts = append(opts, additionalOpts...) return opts } // GetGrpcClientConn 获取一个 gRPC 客户端长连接(支持连接复用) // 对于相同的地址和配置,会复用已存在的连接;如果连接不存在或已关闭,则创建新连接 // 参数 opts 可以传入自定义的拨号选项,如拦截器等 func GetGrpcClientConn(addr string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { // 获取或创建连接池条目 value, _ := connPool.LoadOrStore(addr, &connPoolEntry{}) entry := value.(*connPoolEntry) entry.mu.Lock() defer entry.mu.Unlock() // 检查现有连接是否可用 if entry.conn != nil { state := entry.conn.GetState() // 检查连接是否处于可用状态或可恢复状态 if isConnAvailable(state) { // 检查配置是否一致 return entry.conn, nil } else { entry.conn.Close() // 连接不可用,清理 entry.conn = nil } } // 创建新连接 dialOpts := ClientDialOptions( defaultMaxMsgSize, defaultKeepaliveTime, defaultKeepaliveTimeout, nil, // 不再硬编码拦截器 nil, opts..., // 允许调用方传入自定义选项 ) conn, err := grpc.NewClient(addr, dialOpts...) if err != nil { return nil, fmt.Errorf("failed to create grpc client for address %s: %w", addr, err) } // 保存新连接 entry.conn = conn return conn, nil } // isConnAvailable 检查连接状态是否可用 func isConnAvailable(state connectivity.State) bool { // Ready: 连接就绪 // Idle: 连接空闲但可用 // Connecting: 正在连接,可以等待 // TransientFailure: 暂时失败,不可用 // Shutdown: 已关闭,不可用 return state == connectivity.Ready || state == connectivity.Idle || state == connectivity.Connecting } // CloseGrpcClientConn 关闭指定地址的 gRPC 连接并从连接池中移除 func CloseGrpcClientConn(addr string) error { if value, ok := connPool.LoadAndDelete(addr); ok { entry := value.(*connPoolEntry) entry.mu.Lock() defer entry.mu.Unlock() if entry.conn != nil { return entry.conn.Close() } } return nil } // CloseAllGrpcClientConns 关闭所有连接池中的连接 func CloseAllGrpcClientConns() error { var lastErr error var keys []interface{} // 先收集所有的 key connPool.Range(func(key, value interface{}) bool { keys = append(keys, key) return true }) // 逐个关闭并删除 for _, key := range keys { if value, ok := connPool.LoadAndDelete(key); ok { entry := value.(*connPoolEntry) entry.mu.Lock() if entry.conn != nil { if err := entry.conn.Close(); err != nil { lastErr = err } } entry.mu.Unlock() } } return lastErr } ================================================ FILE: go/net/grpc/grpc_client.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 grpc import "time" // WithMaxMsgSize 设置最大消息大小 func WithMaxMsgSize(maxMsgSize int) GrpcClientOption { return GrpcClientOptionFunc(func(c *GrpcClient) { c.opts.maxMsgSize = maxMsgSize }) } // WithCallTimeout 设置默认调用超时时间 func WithCallTimeout(timeout time.Duration) GrpcClientOption { return GrpcClientOptionFunc(func(c *GrpcClient) { c.opts.callTimeout = timeout }) } // WithKeepaliveTime 设置 keepalive 时间间隔 func WithKeepaliveTime(keepaliveTime time.Duration) GrpcClientOption { return GrpcClientOptionFunc(func(c *GrpcClient) { c.opts.keepaliveTime = keepaliveTime }) } // WithKeepaliveTimeout 设置 keepalive 超时时间 func WithKeepaliveTimeout(keepaliveTimeout time.Duration) GrpcClientOption { return GrpcClientOptionFunc(func(c *GrpcClient) { c.opts.keepaliveTimeout = keepaliveTimeout }) } // WithDisablePrintMethods 设置不需要在调试日志中打印的方法列表 func WithDisablePrintMethods(methods ...string) GrpcClientOption { return GrpcClientOptionFunc(func(c *GrpcClient) { c.opts.disablePrintMethods = methods }) } ================================================ FILE: go/net/grpc/grpc_client.repository.factory.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 grpc import ( "context" "fmt" "time" "github.com/go-playground/validator/v10" resolve_ "github.com/kaydxh/golang/go/net/resolver/resolve" "google.golang.org/grpc" ) type FactoryConfigFunc[T any] func(c *FactoryConfig[T]) error type FactoryConfig[T any] struct { Validator *validator.Validate Addr string Timeout time.Duration //接口处理超时时间 NewServiceClient func(*grpc.ClientConn) T // not include the first call RetryTimes int RetryInterval time.Duration DisablePrintInoutMethods []string } func (fc *FactoryConfig[T]) ApplyOptions(configFuncs ...FactoryConfigFunc[T]) error { for _, f := range configFuncs { err := f(fc) if err != nil { return fmt.Errorf("failed to apply factory config, err: %v", err) } } return nil } func (fc FactoryConfig[T]) Validate() error { valid := fc.Validator if valid == nil { valid = validator.New() } return valid.Struct(fc) } type Repository[T any] struct { Timeout time.Duration Addr string NewServiceClient func(*grpc.ClientConn) T Conn *grpc.ClientConn Client T // not include the first call RetryTimes int RetryInterval time.Duration DisablePrintInoutMethods []string } func (r *Repository[T]) NewConnect(ctx context.Context) (client T, conn *grpc.ClientConn, err error) { var zeroClient T addr := r.Addr address, err := resolve_.ResolveOne(ctx, addr) if err != nil { return zeroClient, nil, err } if address.Addr != "" { addr = address.Addr } conn, err = GetGrpcClientConn(addr) if err != nil { return zeroClient, nil, err } return r.NewServiceClient(conn), conn, nil } func (r *Repository[T]) Close(conn *grpc.ClientConn) (err error) { return conn.Close() } func newRepository[T any](ctx context.Context, fc FactoryConfig[T]) (Repository[T], error) { conn, err := GetGrpcClientConn(fc.Addr) if err != nil { return Repository[T]{}, err } repo := Repository[T]{ Timeout: fc.Timeout, Addr: fc.Addr, NewServiceClient: fc.NewServiceClient, Conn: conn, Client: fc.NewServiceClient(conn), RetryTimes: fc.RetryTimes, RetryInterval: fc.RetryInterval, DisablePrintInoutMethods: fc.DisablePrintInoutMethods, } return repo, nil } type Factory[T any] struct { fc FactoryConfig[T] } func NewFactory[T any](fc FactoryConfig[T], configFuncs ...FactoryConfigFunc[T]) (Factory[T], error) { err := fc.ApplyOptions(configFuncs...) if err != nil { return Factory[T]{}, err } err = fc.Validate() if err != nil { return Factory[T]{}, err } return Factory[T]{fc: fc}, nil } func (f Factory[T]) NewClient(ctx context.Context) (Repository[T], error) { return newRepository(ctx, f.fc) } ================================================ FILE: go/net/grpc/grpc_client.repository.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 grpc import ( "context" context_ "github.com/kaydxh/golang/go/context" time_ "github.com/kaydxh/golang/go/time" "github.com/sirupsen/logrus" ) func (r *Repository[T]) Call(ctx context.Context, f func(ctx context.Context) error) (err error) { logger := logrus.WithContext(ctx) err = time_.RetryWithContext(ctx, func(ctx context.Context) error { ctx, cancel := context_.WithTimeout(ctx, r.Timeout) defer cancel() err = f(ctx) if err != nil { logger.WithError(err).Errorf("failed to call f") return err } return nil }, r.RetryInterval, r.RetryTimes) if err != nil { return err } return nil } ================================================ FILE: go/net/grpc/grpc_client_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 grpc // A GrpcClientOption sets options. type GrpcClientOption interface { apply(*GrpcClient) } // EmptyGrpcClientOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyGrpcClientOption struct{} func (EmptyGrpcClientOption) apply(*GrpcClient) {} // GrpcClientOptionFunc wraps a function that modifies Client into an // implementation of the GrpcClientOption interface. type GrpcClientOptionFunc func(*GrpcClient) func (f GrpcClientOptionFunc) apply(do *GrpcClient) { f(do) } func (o *GrpcClient) ApplyOptions(options ...GrpcClientOption) *GrpcClient { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/grpc/grpc_client_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 grpc_test import ( "testing" "time" grpc_ "github.com/kaydxh/golang/go/net/grpc" ) func TestGetGrpcClientConn(t *testing.T) { var ( serverAddress = "127.0.0.1:8001" ) conn, err := grpc_.GetGrpcClientConn(serverAddress) if err != nil { t.Fatalf("failed to get grpc client conn, err: %v", err) return } defer conn.Close() } func TestNewGrpcClient(t *testing.T) { var ( serverAddress = "127.0.0.1:8001" callTimeout = 5 * time.Second ) gClient, err := grpc_.NewGrpcClient(serverAddress, grpc_.WithCallTimeout(callTimeout)) if err != nil { t.Fatalf("failed to create grpc client, err: %v", err) return } defer gClient.Close() } ================================================ FILE: go/net/grpc/grpc_stats.handler.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 grpc import ( "context" "github.com/sirupsen/logrus" "google.golang.org/grpc/stats" ) type statHandler struct { } // TagRPC can attach some information to the given context. // The context used for the rest lifetime of the RPC will be derived from // the returned context. func (h *statHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { return ctx } // HandleRPC processes the RPC stats. func (h *statHandler) HandleRPC(ctx context.Context, s stats.RPCStats) { logger := logrus.WithContext(ctx) switch v := s.(type) { case *stats.OutHeader: logger.WithField("local_addr", v.LocalAddr).WithField("remote_addr", v.RemoteAddr).Infof("HandleRPC method %v", v.FullMethod) } } // TagConn can attach some information to the given context. // The returned context will be used for stats handling. // For conn stats handling, the context used in HandleConn for this // connection will be derived from the context returned. // For RPC stats handling, // - On server side, the context used in HandleRPC for all RPCs on this // connection will be derived from the context returned. // - On client side, the context is not derived from the context returned. func (s *statHandler) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context { logger := logrus.WithContext(ctx) logger.WithField("local_addr", info.LocalAddr).WithField("remote_addr", info.RemoteAddr).Debugf("tag conn") return ctx } // HandleConn processes the Conn stats. func (s *statHandler) HandleConn(context.Context, stats.ConnStats) { } ================================================ FILE: go/net/grpc/ip.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 grpc import ( "context" "fmt" "net" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" ) // returns IP address from grpc context. // It will lookup IP in X-Forwarded-For and X-Real-IP headers, if both // get empty, lookup IP from peer context func GetIPFromContext(ctx context.Context) (net.IP, error) { // FromIncomingContext returns the incoming metadata in ctx if it exists. md, ok := metadata.FromIncomingContext(ctx) if ok { peerAddr := md.Get("x-real-ip") if len(peerAddr) > 0 { return net.ParseIP(peerAddr[0]), nil } peerAddr = md.Get("x-forwarded-for") if len(peerAddr) > 0 { return net.ParseIP(peerAddr[0]), nil } } //if use proxy, only return proxy address // FromContext returns the peer information in ctx if it exists. peerAddr, ok := peer.FromContext(ctx) if !ok { return nil, fmt.Errorf("unexpected context") } if peerAddr.Addr == net.Addr(nil) { return nil, fmt.Errorf("unexpected err: peer address is nil") } host, _, err := net.SplitHostPort(peerAddr.Addr.String()) if err != nil { return nil, fmt.Errorf("invalid peer host: %v, err: %v", peerAddr.Addr.String(), err) } return net.ParseIP(host), nil } ================================================ FILE: go/net/http/clone.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "mime/multipart" "net/http" "net/url" _ "unsafe" // for go:linkname ) //go:linkname CloneURLValues net/http.cloneURLValues func CloneURLValues(v url.Values) url.Values //go:linkname CloneURL net/http.cloneURL func CloneURL(u *url.URL) *url.URL //go:linkname CloneMultipartForm net/http.cloneMultipartForm func CloneMultipartForm(f *multipart.Form) *multipart.Form //go:linkname CloneMultipartFileHeader net/http.cloneMultipartFileHeader func CloneMultipartFileHeader(fh *multipart.FileHeader) *multipart.FileHeader // CloneOrMakeHeader invokes Header.Clone but if the // result is nil, it'll instead make and return a non-nil Header. //go:linkname CloneOrMakeHeader net/http.cloneOrMakeHeader func CloneOrMakeHeader(hdr http.Header) http.Header ================================================ FILE: go/net/http/example/data.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.13.0 // source: go/net/grpc/example/data.proto package date import ( _ "github.com/golang/protobuf/protoc-gen-go/descriptor" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type NowRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RequestId string `protobuf:"bytes,1,opt,name=request_id,json=RequestId,proto3" json:"request_id,omitempty"` //请求ID } func (x *NowRequest) Reset() { *x = NowRequest{} if protoimpl.UnsafeEnabled { mi := &file_go_net_grpc_example_data_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NowRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*NowRequest) ProtoMessage() {} func (x *NowRequest) ProtoReflect() protoreflect.Message { mi := &file_go_net_grpc_example_data_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NowRequest.ProtoReflect.Descriptor instead. func (*NowRequest) Descriptor() ([]byte, []int) { return file_go_net_grpc_example_data_proto_rawDescGZIP(), []int{0} } func (x *NowRequest) GetRequestId() string { if x != nil { return x.RequestId } return "" } type NowResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RequestId string `protobuf:"bytes,1,opt,name=request_id,json=RequestId,proto3" json:"request_id,omitempty"` // 请求ID Date string `protobuf:"bytes,2,opt,name=date,json=Date,proto3" json:"date,omitempty"` //当前时间 } func (x *NowResponse) Reset() { *x = NowResponse{} if protoimpl.UnsafeEnabled { mi := &file_go_net_grpc_example_data_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NowResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*NowResponse) ProtoMessage() {} func (x *NowResponse) ProtoReflect() protoreflect.Message { mi := &file_go_net_grpc_example_data_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NowResponse.ProtoReflect.Descriptor instead. func (*NowResponse) Descriptor() ([]byte, []int) { return file_go_net_grpc_example_data_proto_rawDescGZIP(), []int{1} } func (x *NowResponse) GetRequestId() string { if x != nil { return x.RequestId } return "" } func (x *NowResponse) GetDate() string { if x != nil { return x.Date } return "" } var File_go_net_grpc_example_data_proto protoreflect.FileDescriptor var file_go_net_grpc_example_data_proto_rawDesc = []byte{ 0x0a, 0x1e, 0x67, 0x6f, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x73, 0x65, 0x61, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x65, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2b, 0x0a, 0x0a, 0x4e, 0x6f, 0x77, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0x40, 0x0a, 0x0b, 0x4e, 0x6f, 0x77, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x44, 0x61, 0x74, 0x65, 0x32, 0x4b, 0x0a, 0x0b, 0x44, 0x61, 0x74, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x3c, 0x0a, 0x03, 0x4e, 0x6f, 0x77, 0x12, 0x18, 0x2e, 0x73, 0x65, 0x61, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x4e, 0x6f, 0x77, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x19, 0x2e, 0x73, 0x65, 0x61, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x4e, 0x6f, 0x77, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x32, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x73, 0x65, 0x61, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2d, 0x73, 0x70, 0x65, 0x63, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3b, 0x64, 0x61, 0x74, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_go_net_grpc_example_data_proto_rawDescOnce sync.Once file_go_net_grpc_example_data_proto_rawDescData = file_go_net_grpc_example_data_proto_rawDesc ) func file_go_net_grpc_example_data_proto_rawDescGZIP() []byte { file_go_net_grpc_example_data_proto_rawDescOnce.Do(func() { file_go_net_grpc_example_data_proto_rawDescData = protoimpl.X.CompressGZIP(file_go_net_grpc_example_data_proto_rawDescData) }) return file_go_net_grpc_example_data_proto_rawDescData } var file_go_net_grpc_example_data_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_go_net_grpc_example_data_proto_goTypes = []interface{}{ (*NowRequest)(nil), // 0: sea.api.date.NowRequest (*NowResponse)(nil), // 1: sea.api.date.NowResponse } var file_go_net_grpc_example_data_proto_depIdxs = []int32{ 0, // 0: sea.api.date.DateService.Now:input_type -> sea.api.date.NowRequest 1, // 1: sea.api.date.DateService.Now:output_type -> sea.api.date.NowResponse 1, // [1:2] is the sub-list for method output_type 0, // [0:1] 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_go_net_grpc_example_data_proto_init() } func file_go_net_grpc_example_data_proto_init() { if File_go_net_grpc_example_data_proto != nil { return } if !protoimpl.UnsafeEnabled { file_go_net_grpc_example_data_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NowRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_go_net_grpc_example_data_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NowResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_go_net_grpc_example_data_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 1, }, GoTypes: file_go_net_grpc_example_data_proto_goTypes, DependencyIndexes: file_go_net_grpc_example_data_proto_depIdxs, MessageInfos: file_go_net_grpc_example_data_proto_msgTypes, }.Build() File_go_net_grpc_example_data_proto = out.File file_go_net_grpc_example_data_proto_rawDesc = nil file_go_net_grpc_example_data_proto_goTypes = nil file_go_net_grpc_example_data_proto_depIdxs = nil } ================================================ FILE: go/net/http/example/data.proto ================================================ syntax = "proto3"; package sea.api.date; import "google/protobuf/descriptor.proto"; option go_package = "github.com/kaydxh/sea/api/openapi-spec/date;date"; service DateService { // 生成当前时间 rpc Now(NowRequest) returns (NowResponse) {}; } message NowRequest { string request_id = 1 [json_name = "RequestId"]; //请求ID } message NowResponse { string request_id = 1 [json_name = "RequestId"]; // 请求ID string date = 2 [json_name = "Date"]; //当前时间 } ================================================ FILE: go/net/http/example/http_client.repository_test.go ================================================ package date_test import ( "testing" "time" "context" http_ "github.com/kaydxh/golang/go/net/http" date_ "github.com/kaydxh/golang/go/net/http/example" ) func TestNowPbJson(t *testing.T) { ctx := context.Background() client, err := http_.NewClient() if err != nil { t.Errorf("failed to new http client, err: %v", err) } factory, err := http_.NewFactory[date_.NowRequest, date_.NowResponse](http_.FactoryConfig{ Url: "http://localhost:10001/Now", Timeout: 5 * time.Second, Client: client, RetryTimes: 3, }, ) if err != nil { t.Errorf("failed to new factory, err: %v", err) } repository, err := factory.NewClient(ctx) if err != nil { t.Errorf("failed to new respository client, err: %v", err) } nowResponse, err := repository.PostPbJson(ctx, &date_.NowRequest{}) if err != nil { t.Errorf("failed to call Now, err: %v", err) } t.Logf("resp: %v", nowResponse) } func TestNowPb(t *testing.T) { ctx := context.Background() client, err := http_.NewClient() if err != nil { t.Errorf("failed to new http client, err: %v", err) } factory, err := http_.NewFactory[date_.NowRequest, date_.NowResponse](http_.FactoryConfig{ Url: "http://localhost:10001/Now", Timeout: 5 * time.Second, Client: client, RetryTimes: 3, }, ) if err != nil { t.Errorf("failed to new factory, err: %v", err) } repository, err := factory.NewClient(ctx) if err != nil { t.Errorf("failed to new respository client, err: %v", err) } nowResponse, err := repository.PostPb(ctx, &date_.NowRequest{}) if err != nil { t.Errorf("failed to call Now, err: %v", err) } t.Logf("resp: %v", nowResponse) } ================================================ FILE: go/net/http/http_client.do.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "context" "io" "net/http" time_ "github.com/kaydxh/golang/go/time" "github.com/sirupsen/logrus" ) func (c *Client) get(ctx context.Context, url string) (*http.Response, error) { return c.HttpDo(ctx, http.MethodGet, url, "", nil, nil, nil) } func (c *Client) post(ctx context.Context, url string, contentType string, headers map[string]string, auth func(r *http.Request) error, body io.Reader, ) (*http.Response, error) { return c.HttpDo(ctx, http.MethodPost, url, contentType, headers, auth, body) } func (c *Client) put(ctx context.Context, url string, contentType string, headers map[string]string, auth func(r *http.Request) error, body io.Reader, ) (*http.Response, error) { return c.HttpDo(ctx, http.MethodPut, url, contentType, headers, auth, body) } func (c *Client) HttpDo(ctx context.Context, method string, url string, contentType string, headers map[string]string, auth func(r *http.Request) error, body io.Reader, ) (*http.Response, error) { req, err := http.NewRequest(method, url, body) if err != nil { return nil, err } if contentType != "" { req.Header.Set("Content-Type", contentType) } for key, value := range headers { req.Header.Set(key, value) } if auth != nil { err = auth(req) if err != nil { return nil, err } } return c.Do(ctx, req) } func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error) { /* err := RequestWithTargetHost(req, c.opts.targetHost) if err != nil { return nil, err } */ tc := time_.New(true) logger := logrus.WithContext(ctx) logger.WithField("target_addr", req.Host).Infof("http do %v", req.URL.Path) summary := func() { tc.Tick(req.Method) logger.WithField("method", req.Method).Infof(tc.String()) } defer summary() return c.Client.Do(req) } ================================================ FILE: go/net/http/http_client.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "bytes" "context" "fmt" "io" "io/ioutil" "log" "net" "net/http" "time" "github.com/gin-gonic/gin/binding" ) type Client struct { http.Client opts struct { // Timeout specifies a time limit for requests made by this // Client. The timeout includes connection time, any // redirects, and reading the response body. The timer remains // running after Get, Head, Post, or Do return and will // interrupt reading of the Response.Body. // // A Timeout of zero means no timeout. // // The Client cancels requests to the underlying Transport // as if the Request's Context ended. // // For compatibility, the Client will also use the deprecated // CancelRequest method on Transport if found. New // RoundTripper implementations should use the Request's Context // for cancellation instead of implementing CancelRequest. timeout time.Duration dialTimeout time.Duration responseHeaderTimeout time.Duration idleConnTimeout time.Duration maxIdleConns int disableKeepAlives bool // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // // The proxy type is determined by the URL scheme. "http", // "https", and "socks5" are supported. If the scheme is empty, // "http" is assumed. // // If Proxy is nil or returns a nil *URL, no proxy is used. //proxy func(*http.Request) (*url.URL, error) // like forward proxy proxyURL string // proxyHost is host:port, or domain, replace host in proxy proxyHost string // targetHost is host:port, redirect to it, like reverse proxy targetHost string ErrorLog *log.Logger } } func NewClient(options ...ClientOption) (*Client, error) { c := &Client{} c.ApplyOptions(options...) transport := DefaultTransportInsecure /* transport := &http.Transport{ // ProxyFromEnvironment returns the URL of the proxy to use for a // given request, as indicated by the environment variables // HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions // thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https // requests. // // The environment values may be either a complete URL or a // "host[:port]", in which case the "http" scheme is assumed. // The schemes "http", "https", and "socks5" are supported. // An error is returned if the value is a different form. // // A nil URL and nil error are returned if no proxy is defined in the // environment, or a proxy should not be used for the given request, // as defined by NO_PROXY. // // As a special case, if req.URL.Host is "localhost" (with or without // a port number), then a nil URL and nil error will be returned. Proxy: http.ProxyFromEnvironment, // skip verify for https TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } */ if c.opts.timeout != 0 { c.Client.Timeout = c.opts.timeout } if c.opts.dialTimeout != 0 { transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { conn, err := net.DialTimeout( network, addr, c.opts.dialTimeout, ) if nil != err { return nil, err } return conn, nil } } if c.opts.responseHeaderTimeout != 0 { transport.ResponseHeaderTimeout = c.opts.responseHeaderTimeout } if c.opts.maxIdleConns != 0 { transport.MaxIdleConns = c.opts.maxIdleConns } if c.opts.idleConnTimeout != 0 { transport.IdleConnTimeout = c.opts.idleConnTimeout } if c.opts.disableKeepAlives { transport.DisableKeepAlives = c.opts.disableKeepAlives } c.Transport = RoundTripFunc(func(req *http.Request) (resp *http.Response, err error) { if c.opts.proxyURL != "" || c.opts.proxyHost != "" { transport.Proxy = ProxyFuncFromContextOrEnvironment proxyUrl := "http://" if c.opts.proxyURL != "" { proxyUrl = c.opts.proxyURL } proxy := &Proxy{ ProxyUrl: proxyUrl, ProxyTarget: c.opts.proxyHost, } req = RequestWithContextProxy(req, proxy) } if c.opts.targetHost != "" { host := &Host{ HostTarget: c.opts.targetHost, ReplaceHostInRequest: true, } req = RequestWithContextTargetHost(req, host) } return RoundTripperWithTarget(transport).RoundTrip(req) }) return c, nil } func (c *Client) Get(ctx context.Context, url string) ([]byte, error) { r, err := c.get(ctx, url) if err != nil { return nil, err } defer r.Body.Close() data, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } return data, nil } func (c *Client) Post( ctx context.Context, url, contentType string, headers map[string]string, body []byte, ) ([]byte, error) { bodyReader := bytes.NewReader(body) return c.PostReader(ctx, url, contentType, headers, nil, bodyReader) } func (c *Client) Put( ctx context.Context, url, contentType string, headers map[string]string, body []byte, ) ([]byte, error) { bodyReader := bytes.NewReader(body) return c.PutReader(ctx, url, contentType, headers, nil, bodyReader) } func (c *Client) PostJson( ctx context.Context, url string, headers map[string]string, body []byte, ) ([]byte, error) { bodyReader := bytes.NewReader(body) return c.PostReader(ctx, url, binding.MIMEJSON, headers, nil, bodyReader) } func (c *Client) PostPb( ctx context.Context, url string, headers map[string]string, body []byte, ) ([]byte, error) { bodyReader := bytes.NewReader(body) return c.PostReader(ctx, url, binding.MIMEPROTOBUF, headers, nil, bodyReader) } func (c *Client) PostJsonWithAuthorize( ctx context.Context, url string, headers map[string]string, auth func(r *http.Request) error, body []byte, ) ([]byte, error) { bodyReader := bytes.NewReader(body) return c.PostReader(ctx, url, binding.MIMEJSON, headers, auth, bodyReader) } func (c *Client) PostReader( ctx context.Context, url, contentType string, headers map[string]string, auth func(r *http.Request) error, body io.Reader, ) ([]byte, error) { return c.HttpReader(ctx, http.MethodPost, url, contentType, headers, auth, body) } func (c *Client) PutReader( ctx context.Context, url, contentType string, headers map[string]string, auth func(r *http.Request) error, body io.Reader, ) ([]byte, error) { return c.HttpReader(ctx, http.MethodPut, url, contentType, headers, auth, body) } func (c *Client) HttpReader( ctx context.Context, method, url, contentType string, headers map[string]string, auth func(r *http.Request) error, body io.Reader, ) ([]byte, error) { r, err := c.HttpDo(ctx, method, url, contentType, headers, auth, body) if err != nil { return nil, err } defer r.Body.Close() data, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } if r.StatusCode >= http.StatusBadRequest { return data, fmt.Errorf("http status code: %v", r.StatusCode) } return data, nil } func (c *Client) logf(format string, args ...interface{}) { if c.opts.ErrorLog != nil { c.opts.ErrorLog.Printf(format, args...) } else { log.Printf(format, args...) } } ================================================ FILE: go/net/http/http_client.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "log" "time" ) func WithTimeout(timeout time.Duration) ClientOption { return ClientOptionFunc(func(c *Client) { c.opts.timeout = timeout }) } func WithResonseHeaderTimeout(responseHeaderTimeout time.Duration) ClientOption { // https://cos.ap-beijing.myqcloud.com return ClientOptionFunc(func(c *Client) { c.opts.responseHeaderTimeout = responseHeaderTimeout }) } func WithMaxIdleConns(maxIdleConns int) ClientOption { return ClientOptionFunc(func(c *Client) { c.opts.maxIdleConns = maxIdleConns }) } func WithIdleConnTimeout(idleConnTimeout time.Duration) ClientOption { return ClientOptionFunc(func(c *Client) { c.opts.idleConnTimeout = idleConnTimeout }) } func WithDisableKeepAlives(disableKeepAlives bool) ClientOption { return ClientOptionFunc(func(c *Client) { c.opts.disableKeepAlives = disableKeepAlives }) } // http://xxx:yyy@goproxy.com func WithProxyURL(proxyURL string) ClientOption { return ClientOptionFunc(func(c *Client) { c.opts.proxyURL = proxyURL }) } //dns:///ai-media-1256936300.cos.ap-guangzhou.myqcloud.com // redirect func WithTargetHost(target string) ClientOption { return ClientOptionFunc(func(c *Client) { c.opts.targetHost = target }) } // replace host in proxy url func WithProxyHost(target string) ClientOption { return ClientOptionFunc(func(c *Client) { c.opts.proxyHost = target }) } // WithLogger func WithLogger(l *log.Logger) ClientOption { return ClientOptionFunc(func(c *Client) { c.opts.ErrorLog = l }) } ================================================ FILE: go/net/http/http_client.repository.factory.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "context" "fmt" "time" "github.com/go-playground/validator/v10" "google.golang.org/protobuf/proto" ) type FactoryConfigFunc func(c *FactoryConfig) error type FactoryConfig struct { Validator *validator.Validate Url string Timeout time.Duration //接口处理超时时间 *Client RetryTimes int RetryInterval time.Duration } func (fc *FactoryConfig) ApplyOptions(configFuncs ...FactoryConfigFunc) error { for _, f := range configFuncs { err := f(fc) if err != nil { return fmt.Errorf("failed to apply factory config, err: %v", err) } } return nil } func (fc FactoryConfig) Validate() error { valid := fc.Validator if valid == nil { valid = validator.New() } return valid.Struct(fc) } type ProtoMessage interface { proto.Message } type Repository[REQ any, RESP any] struct { Url string Timeout time.Duration *Client // not include the first call RetryTimes int RetryInterval time.Duration } func newRepository[REQ any, RESP any](ctx context.Context, fc FactoryConfig) (*Repository[REQ, RESP], error) { repo := &Repository[REQ, RESP]{ Url: fc.Url, Timeout: fc.Timeout, Client: fc.Client, RetryTimes: fc.RetryTimes, RetryInterval: fc.RetryInterval, } return repo, nil } type Factory[REQ any, RESP any] struct { fc FactoryConfig } func NewFactory[REQ any, RESP any](fc FactoryConfig, configFuncs ...FactoryConfigFunc) (Factory[REQ, RESP], error) { err := fc.ApplyOptions(configFuncs...) if err != nil { return Factory[REQ, RESP]{}, err } err = fc.Validate() if err != nil { return Factory[REQ, RESP]{}, err } return Factory[REQ, RESP]{fc: fc}, nil } func (f Factory[REQ, RESP]) NewClient(ctx context.Context) (*Repository[REQ, RESP], error) { return newRepository[REQ, RESP](ctx, f.fc) } ================================================ FILE: go/net/http/http_client.repository.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "context" "fmt" context_ "github.com/kaydxh/golang/go/context" "github.com/kaydxh/golang/go/encoding/protojson" reflect_ "github.com/kaydxh/golang/go/reflect" time_ "github.com/kaydxh/golang/go/time" "github.com/sirupsen/logrus" "google.golang.org/protobuf/proto" ) func (r *Repository[REQ, RESP]) PostPbJson(ctx context.Context, req *REQ) (resp *RESP, err error) { return r.PostPbJsonWithUrl(ctx, r.Url, req) } func (r *Repository[REQ, RESP]) PostPbJsonWithUrl(ctx context.Context, url string, req *REQ) (resp *RESP, err error) { logger := logrus.WithContext(ctx) tc := time_.New(true) summary := func() { tc.Tick("PostPbJson") respProto, ok := any(resp).(proto.Message) if ok { logger.WithField("response", reflect_.TruncateBytes(proto.Clone(respProto))). WithField("cost", tc.String()). Info("recv") } } defer summary() reqProto, ok := any(req).(proto.Message) if !ok { return nil, fmt.Errorf("req is not proto message type") } logger.WithField("request", reflect_.TruncateBytes(proto.Clone(reqProto))).Info("send") reqData, err := protojson.Marshal(reqProto) if err != nil { logger.WithError(err).WithField("req", req).Errorf("failed to marshal request") return resp, err } var respData []byte err = time_.RetryWithContext(ctx, func(ctx context.Context) error { ctx, cancel := context_.WithTimeout(ctx, r.Timeout) defer cancel() respData, err = r.Client.PostJson(ctx, url, nil, reqData) if err != nil { logger.WithError(err).Errorf("failed to post json") return err } return nil }, r.RetryInterval, r.RetryTimes) if err != nil { return resp, err } var zeroResp RESP resp = &zeroResp err = protojson.Unmarshal(respData, any(resp).(proto.Message)) if err != nil { logger.WithError(err).Errorf("failed to unmarshal post response data") return nil, err } return resp, nil } func (r *Repository[REQ, RESP]) PostPb(ctx context.Context, req *REQ) (resp *RESP, err error) { logger := logrus.WithContext(ctx) tc := time_.New(true) summary := func() { tc.Tick("PostPbJson") respProto, ok := any(resp).(proto.Message) if ok { logger.WithField("response", reflect_.TruncateBytes(proto.Clone(respProto))). WithField("cost", tc.String()). Info("recv") } } defer summary() reqProto, ok := any(req).(proto.Message) if !ok { return nil, fmt.Errorf("req is not proto message type") } logger.WithField("request", reflect_.TruncateBytes(proto.Clone(reqProto))).Info("recv") reqData, err := proto.Marshal(reqProto) if err != nil { logger.WithError(err).WithField("req", req).Errorf("failed to marshal request") return resp, err } var respData []byte err = time_.RetryWithContext(ctx, func(ctx context.Context) error { ctx, cancel := context_.WithTimeout(ctx, r.Timeout) defer cancel() respData, err = r.Client.PostPb(ctx, r.Url, nil, reqData) if err != nil { logger.WithError(err).Errorf("failed to post json, url: %v", r.Url) return err } return nil }, r.RetryInterval, r.RetryTimes) if err != nil { return resp, err } var zeroResp RESP resp = &zeroResp err = proto.Unmarshal(respData, any(resp).(proto.Message)) if err != nil { logger.WithError(err).Errorf("failed to unmarshal post response data") return nil, err } return resp, nil } /* func (r *Repository[REQ, RESP]) Do(ctx context.Context, method string, contentType string, req *REQ) (resp *RESP, err error) { logger := logrus.WithContext(ctx) tc := time_.New(true) summary := func() { tc.Tick("PostPbJson") respProto, ok := any(resp).(proto.Message) if ok { logger.WithField("response", reflect_.TruncateBytes(proto.Clone(respProto))). WithField("cost", tc.String()). Info("recv") } } defer summary() reqProto, ok := any(req).(proto.Message) if !ok { return nil, fmt.Errorf("req is not proto message type") } logger.WithField("request", reflect_.TruncateBytes(proto.Clone(reqProto))).Info("recv") var ( reqData []byte respData []byte ) switch contentType { case binding.MIMEJSON: reqData, err = protojson.Marshal(reqProto) case binding.MIMEPROTOBUF: reqData, err = proto.Marshal(reqProto) default: reqData, err = protojson.Marshal(reqProto) } if err != nil { logger.WithError(err).WithField("req", req).Errorf("failed to marshal request") return resp, err } err = time_.RetryWithContext(ctx, func(ctx context.Context) error { ctx, cancel := context_.WithTimeout(ctx, r.Timeout) defer cancel() respData, err = r.Client.PostPb(r.Url, nil, reqData) if err != nil { logger.WithError(err).Errorf("failed to post json") return err } return nil }, r.RetryInterval, r.RetryTimes) if err != nil { return resp, err } var zeroResp RESP resp = &zeroResp err = proto.Unmarshal(respData, any(resp).(proto.Message)) if err != nil { logger.WithError(err).Errorf("failed to unmarshal post response data") return nil, err } return resp, nil } */ ================================================ FILE: go/net/http/http_client_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http // A ClientOption sets options. type ClientOption interface { apply(*Client) } // EmptyClientOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyClientOption struct{} func (EmptyClientOption) apply(*Client) {} // ClientOptionFunc wraps a function that modifies Client into an // implementation of the ClientOption interface. type ClientOptionFunc func(*Client) func (f ClientOptionFunc) apply(do *Client) { f(do) } // sample code for option, default for nothing to change func _ClientOptionWithDefault() ClientOption { return ClientOptionFunc(func(*Client) { // nothing to change }) } func (o *Client) ApplyOptions(options ...ClientOption) *Client { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/http/http_client_proxy.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "net/http" url_ "github.com/kaydxh/golang/go/net/url" ) func RequestWithTargetHost(req *http.Request, target string) error { if target == "" { return nil } newUrl, err := url_.ResolveWithTarget(req.Context(), req.URL, target) if err != nil { return err } req.URL = newUrl req.Host = newUrl.Host return nil } func NewClientWithTargetHost(target string, opts ...ClientOption) *Client { opts = append(opts, WithTargetHost(target)) c, _ := NewClient(opts...) return c } ================================================ FILE: go/net/http/http_client_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http_test import ( "testing" "time" http_ "github.com/kaydxh/golang/go/net/http" "golang.org/x/net/context" "gotest.tools/v3/assert" ) func TestHttpClientGet(t *testing.T) { ctx := context.Background() client, err := http_.NewClient(http_.WithTimeout(5 * time.Second)) if err != nil { t.Fatalf("expect nil, got %v", err) } testCases := []struct { url string expected bool }{ { url: "http://127.0.0.1", expected: true, }, { url: "http://127.0.0.2", expected: false, }, } for _, test := range testCases { data, err := client.Get(ctx, test.url) if test.expected { assert.NilError(t, err) } else { assert.Assert(t, err != nil) // NotNil t.Logf("got %v", err) } t.Logf("response data: %v", string(data)) } } func TestHttpClientGetWithProxy(t *testing.T) { ctx := context.Background() client, err := http_.NewClient(http_.WithTimeout(5*time.Second), http_.WithTargetHost("dns:///ai-media-1256936300.cos.ap-guangzhou.myqcloud.com")) if err != nil { t.Fatalf("expect nil, got %v", err) } testCases := []struct { url string expected bool }{ { //url: "https://ai-media-1256936300.cos.ap-guangzhou.myqcloud.com/find.sh?q-sign-algorithm=sha1&q-ak=AKIDCDyve81SJuISPkMq0IukLg7tupWyoqCg&q-sign-time=1659955959;8640000001659870000&q-key-time=1659955959;8640000001659870000&q-header-list=&q-url-param-list=&q-signature=5695f17ee30c3cd2d37197c773a445eda8a70c8c", url: "http://127.0.0.1/find.sh?q-sign-algorithm=sha1&q-ak=AKIDCDyve81SJuISPkMq0IukLg7tupWyoqCg&q-sign-time=1659955959;8640000001659870000&q-key-time=1659955959;8640000001659870000&q-header-list=&q-url-param-list=&q-signature=5695f17ee30c3cd2d37197c773a445eda8a70c8c", expected: true, }, } for _, test := range testCases { data, err := client.Get(ctx, test.url) if test.expected { assert.NilError(t, err) } else { assert.Assert(t, err != nil) // NotNil t.Logf("got %v", err) } t.Logf("response data size: %v", len(data)) } } func TestHttpClientPost(t *testing.T) { ctx := context.Background() client, err := http_.NewClient(http_.WithTimeout(5 * time.Second)) if err != nil { t.Fatalf("expect nil, got %v", err) } testCases := []struct { url string data []byte expected bool }{ { url: "http://127.0.0.1", data: []byte("hello world test1"), expected: true, }, { url: "http://127.0.0.2", data: []byte("hello world test2"), expected: false, }, } for _, test := range testCases { data, err := client.Post(ctx, test.url, "application/text", nil, test.data) if test.expected { assert.NilError(t, err) } else { assert.Assert(t, err != nil) // NotNil t.Logf("got %v", err) } t.Logf("response data: %v", string(data)) } } ================================================ FILE: go/net/http/http_error.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "fmt" "net/http" ) func ErrorFromHttp(code int) error { if code >= http.StatusOK && code < http.StatusBadRequest { return nil } return fmt.Errorf("unexpected http status code: %v", code) } ================================================ FILE: go/net/http/http_handler_chain.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http // A HandlerChainOption sets options. type HandlerChainOption interface { apply(*HandlerChain) } // EmptyHandlerChainOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyHandlerChainOption struct{} func (EmptyHandlerChainOption) apply(*HandlerChain) {} // HandlerChainOptionFunc wraps a function that modifies HandlerChain into an // implementation of the HandlerChainOption interface. type HandlerChainOptionFunc func(*HandlerChain) func (f HandlerChainOptionFunc) apply(do *HandlerChain) { f(do) } // sample code for option, default for nothing to change func _HandlerChainOptionWithDefault() HandlerChainOption { return HandlerChainOptionFunc(func(*HandlerChain) { // nothing to change }) } func (o *HandlerChain) ApplyOptions(options ...HandlerChainOption) *HandlerChain { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/http/http_handler_interceptor.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "net/http" runtime_ "github.com/kaydxh/golang/go/runtime" ) type HandlerInterceptor struct { //http middleware Interceptor func(h http.Handler) http.Handler } func NewHandlerInterceptor(opts ...HandlerInterceptorOption) *HandlerInterceptor { handers := &HandlerInterceptor{} handers.ApplyOptions(opts...) return handers } type HandlerChain struct { //invoke before http handler PreHandlers []func(w http.ResponseWriter, r *http.Request) error Handlers []HandlerInterceptor //invoke after http handler PostHandlers []func(w http.ResponseWriter, r *http.Request) } func NewHandlerChain(opts ...HandlerChainOption) *HandlerChain { c := &HandlerChain{} c.ApplyOptions(opts...) return c } func (c *HandlerChain) WrapH(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer runtime_.Recover() for _, preH := range c.PreHandlers { err := preH(w, r) if err != nil { // assume PreHandler already process response by self return } } // reverse iterate handlers, so called handler as registed order for i := len(c.Handlers) - 1; i >= 0; i-- { // filter interceptor is nil if c.Handlers[i].Interceptor != nil { next = c.Handlers[i].Interceptor(next) } } next.ServeHTTP(w, r) for _, postH := range c.PostHandlers { postH(w, r) } }) } ================================================ FILE: go/net/http/http_handler_interceptor.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http // A HandlerInterceptorOption sets options. type HandlerInterceptorOption interface { apply(*HandlerInterceptor) } // EmptyHandlerInterceptorOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyHandlerInterceptorOption struct{} func (EmptyHandlerInterceptorOption) apply(*HandlerInterceptor) {} // HandlerInterceptorOptionFunc wraps a function that modifies HandlerInterceptor into an // implementation of the HandlerInterceptorOption interface. type HandlerInterceptorOptionFunc func(*HandlerInterceptor) func (f HandlerInterceptorOptionFunc) apply(do *HandlerInterceptor) { f(do) } // sample code for option, default for nothing to change func _HandlerInterceptorOptionWithDefault() HandlerInterceptorOption { return HandlerInterceptorOptionFunc(func(*HandlerInterceptor) { // nothing to change }) } func (o *HandlerInterceptor) ApplyOptions(options ...HandlerInterceptorOption) *HandlerInterceptor { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/http/http_host_context.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 http import ( "context" "fmt" "net/url" "github.com/kaydxh/golang/go/net/resolver" ) type hostContextKey struct{} type Host struct { HostTarget string ReplaceHostInRequest bool HostTargetAddrResolved resolver.Address } func FromContextHost(ctx context.Context) *Host { host, _ := ctx.Value(hostContextKey{}).(*Host) return host } func WithContextHost(ctx context.Context, host *Host) context.Context { if host == nil { panic("nil host") } return context.WithValue(ctx, hostContextKey{}, host) } func ParseTargetUrl(host string) (*url.URL, error) { if host == "" { return nil, nil } hostURL, err := url.Parse(host) if err != nil { return nil, fmt.Errorf("invalid host address %q: %v", host, err) } return hostURL, nil } ================================================ FILE: go/net/http/http_proxy_context.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 http import ( "context" "fmt" "net/url" "github.com/kaydxh/golang/go/net/resolver" ) type proxyContextKey struct{} type Proxy struct { ProxyUrl string ProxyTarget string ProxyAddrResolved resolver.Address } func FromContextProxy(ctx context.Context) *Proxy { proxy, _ := ctx.Value(proxyContextKey{}).(*Proxy) return proxy } func WithContextProxy(ctx context.Context, proxy *Proxy) context.Context { if proxy == nil { panic("nil proxy") } return context.WithValue(ctx, proxyContextKey{}, proxy) } func ParseProxyUrl(proxy string) (*url.URL, error) { if proxy == "" { return nil, nil } proxyURL, err := url.Parse(proxy) if err != nil || (proxyURL.Scheme != "http" && proxyURL.Scheme != "https" && proxyURL.Scheme != "socks5") { //default use http:// if proxyURL, err := url.Parse("http://" + proxy); err == nil { return proxyURL, nil } } if err != nil { return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err) } return proxyURL, nil } ================================================ FILE: go/net/http/http_request_id.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "context" "net/http" context_ "github.com/kaydxh/golang/go/context" ) // RequestIdKey is metadata key name for request ID const ( DefaultHTTPRequestIDKey = "X-Request-ID" DefaultHTTPTraceIDKey = "X-Traceid" ) func ExtractRequestIdHTTPAndContext(r *http.Request) string { return ExtractHTTPAndContext(r, DefaultHTTPRequestIDKey) } func ExtractTraceIdHTTPAndContext(r *http.Request) string { return ExtractHTTPAndContext(r, DefaultHTTPTraceIDKey) } func ExtractHTTPAndContext(r *http.Request, key string) string { if value := ExtractFromHTTP(r, key); value != "" { return value } return context_.ExtractFromContext(r.Context(), key) } func ExtractFromHTTP(r *http.Request, key string) string { if value := r.Header.Get(key); value != "" { return value } if value := r.URL.Query().Get(key); value != "" { return value } if value := r.FormValue(key); value != "" { return value } if value := r.PostFormValue(key); value != "" { return value } return "" } /* func ExtractRequestIDFromContext(ctx context.Context) string { if v, ok := ctx.Value(DefaultHTTPRequestIDKey).(string); ok { return v } return "" } func ExtractFromContext(ctx context.Context, key string) string { switch requestIDs := ctx.Value(key).(type) { case string: if requestIDs != "" { return requestIDs } case []string: if len(requestIDs) > 0 { return requestIDs[0] } default: return "" } return "" } */ func SetPairContext(r *http.Request, key, value string) *http.Request { ctx := context.WithValue(r.Context(), key, value) r = r.WithContext(ctx) return r } func SetRequestIdContext(r *http.Request, requestID string) *http.Request { return SetPairContext(r, DefaultHTTPRequestIDKey, requestID) } func SetTraceIdContext(r *http.Request, traceID string) *http.Request { return SetPairContext(r, DefaultHTTPTraceIDKey, traceID) } ================================================ FILE: go/net/http/http_round_trip.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 http import "net/http" type RoundTripFunc func(req *http.Request) (resp *http.Response, err error) func (f RoundTripFunc) RoundTrip(req *http.Request) (resp *http.Response, err error) { return f(req) } ================================================ FILE: go/net/http/http_transport.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 http import ( "crypto/tls" "net" "net/http" "time" ) var DefaultTransportInsecure = &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, // skip verify for https TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } var DefaultTransportInsecureWithHostAndProxy = RoundTripperWithTarget(DefaultTransportInsecureWithProxy) ================================================ FILE: go/net/http/http_transport.host.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 http import ( "net/http" resolve_ "github.com/kaydxh/golang/go/net/resolver/resolve" "github.com/sirupsen/logrus" ) func RequestWithContextTargetHost(req *http.Request, target *Host) *http.Request { if target == nil { return req } return req.WithContext(WithContextHost(req.Context(), target)) } func TargetHostFuncFromContext(req *http.Request) error { host := FromContextHost(req.Context()) if host == nil || host.HostTarget == "" { return nil } if req.URL == nil { return nil } if host.HostTarget == "" { return nil } // replace host of host if target of host if resolved address, err := resolve_.ResolveOne(req.Context(), host.HostTarget) if err != nil { return err } if address.Addr != "" { req.URL.Host = address.Addr } host.HostTargetAddrResolved = address if host.ReplaceHostInRequest { req.Host = req.URL.Host } return nil } func RoundTripperWithTarget(rt http.RoundTripper) http.RoundTripper { return RoundTripFunc(func(req *http.Request) (resp *http.Response, err error) { logger := logrus.WithContext(req.Context()) defer func() { logger.Infof("http request host: %v", req.Host) }() err = TargetHostFuncFromContext(req) if err != nil { return nil, err } return rt.RoundTrip(req) }) } var DefaultTransportInsecureWithHost = RoundTripperWithTarget(DefaultTransportInsecure) ================================================ FILE: go/net/http/http_transport.proxy.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 http import ( "crypto/tls" "net" "net/http" "net/url" "time" resolve_ "github.com/kaydxh/golang/go/net/resolver/resolve" "github.com/sirupsen/logrus" ) func RequestWithContextProxy(req *http.Request, proxy *Proxy) *http.Request { if proxy == nil { return req } return req.WithContext(WithContextProxy(req.Context(), proxy)) } func ProxyFuncFromContextOrEnvironment(req *http.Request) (*url.URL, error) { logger := logrus.WithContext(req.Context()) proxy := FromContextProxy(req.Context()) if proxy == nil || proxy.ProxyUrl == "" { return http.ProxyFromEnvironment(req) } defer func() { logger.Infof("http request proxy: %v", proxy) }() proxyUrl, err := ParseProxyUrl(proxy.ProxyUrl) if err != nil { return nil, err } if proxyUrl == nil { return nil, nil } if proxy.ProxyTarget == "" { return proxyUrl, nil } // replace host of proxy if target of proxy if resolved address, err := resolve_.ResolveOne(req.Context(), proxy.ProxyTarget) if err != nil { return nil, err } if address.Addr != "" { proxyUrl.Host = address.Addr } proxy.ProxyAddrResolved = address return proxyUrl, nil } var DefaultTransportInsecureWithProxy http.RoundTripper = &http.Transport{ Proxy: ProxyFuncFromContextOrEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, // skip verify for https TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } ================================================ FILE: go/net/http/ip.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "fmt" "net" "net/http" "strings" ) // returns IP address from request. // It will lookup IP in X-Forwarded-For and X-Real-IP headers. func GetIPFromRequest(r *http.Request) (net.IP, error) { if r == nil { return nil, fmt.Errorf("http request is nil") } ip := r.Header.Get("X-Forwarded-For") if ip != "" { parts := strings.SplitN(ip, ",", 2) part := strings.TrimSpace(parts[0]) return net.ParseIP(part), nil } ip = strings.TrimSpace(r.Header.Get("X-Real-IP")) if ip != "" { return net.ParseIP(ip), nil } remoteAddr := strings.TrimSpace(r.RemoteAddr) host, _, err := net.SplitHostPort(remoteAddr) if err != nil { return net.ParseIP(remoteAddr), err } return net.ParseIP(host), nil } ================================================ FILE: go/net/http/response_writer.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 http import ( "bytes" "fmt" "net/http" ) // ResponseWriterWrapper type ResponseWriterWrapper struct { w http.ResponseWriter body bytes.Buffer statusCode int } func NewResponseWriterWrapper(w http.ResponseWriter) *ResponseWriterWrapper { return &ResponseWriterWrapper{ w: w, statusCode: http.StatusOK, } } func (rww *ResponseWriterWrapper) Write(buf []byte) (int, error) { rww.body.Write(buf) return rww.w.Write(buf) } // Header function overwrites the http.ResponseWriter Header() function func (rww *ResponseWriterWrapper) Header() http.Header { return rww.w.Header() } // WriteHeader function overwrites the http.ResponseWriter WriteHeader() function func (rww *ResponseWriterWrapper) WriteHeader(statusCode int) { rww.statusCode = statusCode rww.w.WriteHeader(statusCode) } // BodyBytes 返回已写入响应的原始 body 字节切片(不包含 headers 和 status code)。 // 返回的是底层缓冲区的引用,调用方不应修改;如需长期持有请自行拷贝。 func (rww *ResponseWriterWrapper) BodyBytes() []byte { return rww.body.Bytes() } // StatusCode 返回当前响应的 HTTP 状态码。 func (rww *ResponseWriterWrapper) StatusCode() int { return rww.statusCode } // String function pack respose header, http status code and body func (rww *ResponseWriterWrapper) String() string { var buf bytes.Buffer buf.WriteString("Headers:") for k, v := range rww.w.Header() { buf.WriteString(fmt.Sprintf("%s: %v", k, v)) } buf.WriteString(fmt.Sprintf(" Status Code:%d", rww.statusCode)) buf.WriteString(" Body:") buf.WriteString(rww.body.String()) return buf.String() } ================================================ FILE: go/net/ip.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 net import ( "context" "errors" "fmt" "net" "os" "strconv" hash_ "github.com/kaydxh/golang/go/encoding/hash" os_ "github.com/kaydxh/golang/go/os" ) // This code is borrowed from https://github.com/uber/tchannel-go/blob/dev/localip.go // scoreAddr scores how likely the given addr is to be a remote address and returns the // IP to use when listening. Any address which receives a negative score should not be used. // Scores are calculated as: // -1 for any unknown IP addresses. // +300 for IPv4 addresses // +100 for non-local addresses, extra +100 for "up" interaces. func scoreAddr(iface net.Interface, addr net.Addr) (int, net.IP) { var ip net.IP if netAddr, ok := addr.(*net.IPNet); ok { ip = netAddr.IP } else if netIP, ok := addr.(*net.IPAddr); ok { ip = netIP.IP } else { return -1, nil } var score int if ip.To4() != nil { score += 300 } if iface.Flags&net.FlagLoopback == 0 && !ip.IsLoopback() { score += 100 if iface.Flags&net.FlagUp != 0 { score += 100 } } return score, ip } // HostIP tries to find an IP that can be used by other machines to reach this machine. func GetHostIP() (net.IP, error) { interfaces, err := net.Interfaces() if err != nil { return nil, err } bestScore := -1 var bestIP net.IP // Select the highest scoring IP as the best IP. for _, iface := range interfaces { addrs, err := iface.Addrs() if err != nil { // Skip this interface if there is an error. continue } for _, addr := range addrs { score, ip := scoreAddr(iface, addr) if score > bestScore { bestScore = score bestIP = ip } } } if bestScore == -1 { return nil, errors.New("no addresses to listen on") } return bestIP, nil } func GetLocalFirstIP() (string, error) { ips, err := GetLocalIPs() if err != nil { return "", err } if len(ips) == 0 { return "", fmt.Errorf("no valid ip") } return ips[0], nil } func GetLocalIPs() ([]string, error) { localAddrs, err := GetLocalAddrs() if err != nil { return nil, err } var ips []string for _, addr := range localAddrs { if addr.IP.To4() != nil && !addr.IP.IsLoopback() { ips = append(ips, addr.IP.String()) } } return ips, nil } func GetLocalAddrs() ([]*net.IPNet, error) { var localAddrs []*net.IPNet addrs, err := net.InterfaceAddrs() if err != nil { return nil, err } for _, addr := range addrs { ipNet, ok := addr.(*net.IPNet) if ok { localAddrs = append(localAddrs, ipNet) } } return localAddrs, nil } // IsIPv4 returns if netIP is IPv4. func IsIPv4(netIP net.IP) bool { return netIP != nil && netIP.To4() != nil } func IsIPv4String(ip string) bool { netIP := ParseIP(ip) return IsIPv4(netIP) } func LookupHostIPv4(host string) (addrs []string, err error) { return LookupHostIPv4WithContext(context.Background(), host) } func LookupHostIPv4WithContext(ctx context.Context, host string) (addrs []string, err error) { ips, err := net.DefaultResolver.LookupHost(ctx, host) if err != nil { return } for _, ip := range ips { if IsIPv4String(ip) { addrs = append(addrs, ip) } } return addrs, err } // SplitHostIntPort split host and integral port func SplitHostIntPort(s string) (string, int, error) { host, port, err := net.SplitHostPort(s) if err != nil { return "", 0, err } portInt, err := strconv.Atoi(port) if err != nil { return "", 0, err } return host, portInt, err } // parseTarget takes the user input target string and default port, returns formatted host and port info. // If target doesn't specify a port, set the port to be the defaultPort. // If target is in IPv6 format and host-name is enclosed in square brackets, brackets // are stripped when setting the host. // examples: // target: "www.google.com" defaultPort: "443" returns host: "www.google.com", port: "443" // target: "ipv4-host:80" defaultPort: "443" returns host: "ipv4-host", port: "80" // target: "[ipv6-host]" defaultPort: "443" returns host: "ipv6-host", port: "443" // target: ":80" defaultPort: "443" returns host: "localhost", port: "80" func ParseTarget(target, defaultPort string) (host, port string, err error) { if target == "" { return "", "", fmt.Errorf("target is empty") } if ip := net.ParseIP(target); ip != nil { // target is an IPv4 or IPv6(without brackets) address return target, defaultPort, nil } if host, port, err = net.SplitHostPort(target); err == nil { if port == "" { // If the port field is empty (target ends with colon), e.g. "[::1]:", this is an error. return "", "", fmt.Errorf("missing port after port-separator colon") } // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port if host == "" { // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed. host = "localhost" } return host, port, nil } if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil { // target doesn't have port return host, port, nil } return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err) } // 1 get k8s pod name // 2 get ip:pid func GetServerName() string { serverName := fmt.Sprintf("%v:%v", os.Getenv("POD_NAMESPACE"), os.Getenv("POD_NAME")) if serverName == ":" { ip, _ := GetHostIP() pid := os_.GetProcId() return fmt.Sprintf("%s:%v", ip.String(), pid) } return serverName } func GetServerId() uint32 { return hash_.HashCode(GetServerName()) } ================================================ FILE: go/net/ip_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 net_test import ( "net" "testing" net_ "github.com/kaydxh/golang/go/net" "github.com/stretchr/testify/assert" ) func TestGetLocalAddrs(t *testing.T) { addrs, err := net_.GetLocalAddrs() if err != nil { t.Fatalf("failed to get local addrs, err: %v", err) return } t.Logf("addrs: %v", addrs) } func TestGetLocalIPs(t *testing.T) { ips, err := net_.GetLocalIPs() if err != nil { t.Fatalf("failed to get local addrs, err: %v", err) return } t.Logf("ips: %v", ips) } func TestGetLocalFirstIP(t *testing.T) { ip, err := net_.GetLocalFirstIP() if err != nil { t.Fatalf("failed to get local first addr, err: %v", err) return } t.Logf("ip: %v", ip) } func TestGetHostIP(t *testing.T) { ip, err := net_.GetHostIP() if err != nil { t.Fatalf("failed to get host ip, err: %v", err) return } t.Logf("ip: %v", ip.String()) } func TestIsIPv4String(t *testing.T) { isIPv4 := net_.IsIPv4String("199.591.149.232") assert.Equal(t, true, isIPv4) t.Logf("ipv4: %v", isIPv4) } func TestLookupHost(t *testing.T) { ips, err := net.LookupHost("www.google.com") if err != nil { t.Fatalf("failed to get host ip, err: %v", err) return } t.Logf("ips: %v", ips) } func TestLookupHostIPv4(t *testing.T) { ips, err := net_.LookupHostIPv4("www.google.com") if err != nil { t.Fatalf("failed to get host ip, err: %v", err) return } t.Logf("ips: %v", ips) } func TestGetServerName(t *testing.T) { serverName := net_.GetServerName() t.Logf("serverName: %v", serverName) } ================================================ FILE: go/net/mac.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 net import ( "fmt" "net" ) func GetLocalFirstMac() (string, error) { interfaces, err := net.Interfaces() if err != nil { return "", err } var macs []string for _, netInterface := range interfaces { mac := netInterface.HardwareAddr.String() if len(mac) == 0 { continue } else { macs = append(macs, mac) } } if len(macs) == 0 { return "", fmt.Errorf("no valid mac") } return macs[0], nil } func GetLocalMacs() ([]string, error) { interfaces, err := net.Interfaces() if err != nil { return nil, err } var macs []string for _, netInterface := range interfaces { mac := netInterface.HardwareAddr.String() if len(mac) == 0 { continue } else { macs = append(macs, mac) } } return macs, nil } ================================================ FILE: go/net/mac_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 net_test import ( "testing" net_ "github.com/kaydxh/golang/go/net" ) func TestGetLocalMacs(t *testing.T) { macs, err := net_.GetLocalMacs() if err != nil { t.Fatalf("failed to get local addrs, err: %v", err) return } t.Logf("macs: %v", macs) } func TestGetLocalFirstMac(t *testing.T) { mac, err := net_.GetLocalFirstMac() if err != nil { t.Fatalf("failed to get local first addr, err: %v", err) return } t.Logf("mac: %v", mac) } ================================================ FILE: go/net/parse.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 net import "net" // ParseIP parses s as an IP address, returning the result. // The string s can be in IPv4 dotted decimal ("192.0.2.1"), IPv6 // ("2001:db8::68"), or IPv4-mapped IPv6 ("::ffff:192.0.2.1") form. // If s is not a valid textual representation of an IP address, // ParseIP returns nil. func ParseIP(s string) net.IP { for i := 0; i < len(s); i++ { switch s[i] { case '.': return parseIPv4(s) case ':': return parseIPv6(s) } } return nil } // Parse IPv4 address (d.d.d.d). func parseIPv4(s string) net.IP { var p [net.IPv4len]byte for i := 0; i < net.IPv4len; i++ { if len(s) == 0 { // Missing octets. return nil } if i > 0 { if s[0] != '.' { return nil } s = s[1:] } n, c, ok := dtoi(s) if !ok || n > 0xFF { return nil } // // NOTE: This correct check was added for go-1.17, but is a // backwards-incompatible change for kubernetes users, who might have // stored data which uses these leading zeroes already. // // See https://issue.k8s.io/100895 // //if c > 1 && s[0] == '0' { // // Reject non-zero components with leading zeroes. // return nil //} s = s[c:] p[i] = byte(n) } if len(s) != 0 { return nil } return net.IPv4(p[0], p[1], p[2], p[3]) } // parseIPv6 parses s as a literal IPv6 address described in RFC 4291 // and RFC 5952. func parseIPv6(s string) (ip net.IP) { ip = make(net.IP, net.IPv6len) ellipsis := -1 // position of ellipsis in ip // Might have leading ellipsis if len(s) >= 2 && s[0] == ':' && s[1] == ':' { ellipsis = 0 s = s[2:] // Might be only ellipsis if len(s) == 0 { return ip } } // Loop, parsing hex numbers followed by colon. i := 0 for i < net.IPv6len { // Hex number. n, c, ok := xtoi(s) if !ok || n > 0xFFFF { return nil } // If followed by dot, might be in trailing IPv4. if c < len(s) && s[c] == '.' { if ellipsis < 0 && i != net.IPv6len-net.IPv4len { // Not the right place. return nil } if i+net.IPv4len > net.IPv6len { // Not enough room. return nil } ip4 := parseIPv4(s) if ip4 == nil { return nil } ip[i] = ip4[12] ip[i+1] = ip4[13] ip[i+2] = ip4[14] ip[i+3] = ip4[15] s = "" i += net.IPv4len break } // Save this 16-bit chunk. ip[i] = byte(n >> 8) ip[i+1] = byte(n) i += 2 // Stop at end of string. s = s[c:] if len(s) == 0 { break } // Otherwise must be followed by colon and more. if s[0] != ':' || len(s) == 1 { return nil } s = s[1:] // Look for ellipsis. if s[0] == ':' { if ellipsis >= 0 { // already have one return nil } ellipsis = i s = s[1:] if len(s) == 0 { // can be at end break } } } // Must have used entire string. if len(s) != 0 { return nil } // If didn't parse enough, expand ellipsis. if i < net.IPv6len { if ellipsis < 0 { return nil } n := net.IPv6len - i for j := i - 1; j >= ellipsis; j-- { ip[j+n] = ip[j] } for j := ellipsis + n - 1; j >= ellipsis; j-- { ip[j] = 0 } } else if ellipsis >= 0 { // Ellipsis must represent at least one 0 group. return nil } return ip } // Bigger than we need, not too big to worry about overflow const big = 0xFFFFFF // Decimal to integer. // Returns number, characters consumed, success. func dtoi(s string) (n int, i int, ok bool) { n = 0 for i = 0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ { n = n*10 + int(s[i]-'0') if n >= big { return big, i, false } } if i == 0 { return 0, 0, false } return n, i, true } // Hexadecimal to integer. // Returns number, characters consumed, success. func xtoi(s string) (n int, i int, ok bool) { n = 0 for i = 0; i < len(s); i++ { if '0' <= s[i] && s[i] <= '9' { n *= 16 n += int(s[i] - '0') } else if 'a' <= s[i] && s[i] <= 'f' { n *= 16 n += int(s[i]-'a') + 10 } else if 'A' <= s[i] && s[i] <= 'F' { n *= 16 n += int(s[i]-'A') + 10 } else { break } if n >= big { return 0, i, false } } if i == 0 { return 0, i, false } return n, i, true } ================================================ FILE: go/net/resolver/build.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver import ( "context" "net" ) // Address represents a server the client connects to. // // Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type Address struct { // Addr is the server address on which a connection will be established. Addr string // ServerName is the name of this address. // If non-empty, the ServerName is used as the transport certification authority for // the address, instead of the hostname from the Dial target string. In most cases, // this should not be set. // // If Type is GRPCLB, ServerName should be the name of the remote load // balancer, not the name of the backend. // // WARNING: ServerName must only be populated with trusted values. It // is insecure to populate it with data from untrusted inputs since untrusted // values could be used to bypass the authority checks performed by TLS. ServerName string } // State contains the current Resolver state relevant to the ClientConn. type State struct { // Addresses is the latest set of resolved addresses for the target. Addresses []Address } // ClientConn contains the callbacks for resolver to notify any updates // to the gRPC ClientConn. // // This interface is to be implemented by gRPC. Users should not need a // brand new implementation of this interface. For the situations like // testing, the new implementation should embed this interface. This allows // gRPC to add new methods to this interface. type ClientConn interface { // UpdateState updates the state of the ClientConn appropriately. UpdateState(State) error // ReportError notifies the ClientConn that the Resolver encountered an // error. The ClientConn will notify the load balancer and begin calling // ResolveNow on the Resolver with exponential backoff. ReportError(error) } type ResolverBuildOptions struct { // if cc is not nil, will update client connection state when resolved Cc ClientConn // Dialer is the custom dialer used by the ClientConn for dialling the // target gRPC service (set via WithDialer). In cases where a name // resolution service requires the same dialer, the resolver may use this // field. In most cases though, it is not appropriate, and this field may // be ignored. Dialer func(context.Context, string) (net.Conn, error) } /* type ResolverBuild struct { Opts ResolverBuildOptions } func NewResolverBuild() { } */ // Builder creates a resolver that will be used to watch name resolution updates. type Builder interface { // Build creates a new resolver for the given target // // gRPC dial calls Build synchronously, and fails if the returned error is // not nil. // Note: only call once for one schema, or will memory leak Build(target Target, opts ...ResolverBuildOption) (Resolver, error) // Scheme returns the scheme supported by this resolver. // Scheme is defined at https://github.com/grpc/grpc/blob/master/doc/naming.md. Scheme() string } ================================================ FILE: go/net/resolver/build.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver import ( "context" "net" ) func WithBuildDialer(dialer func(context.Context, string) (net.Conn, error)) ResolverBuildOptionFunc { return ResolverBuildOptionFunc(func(b *ResolverBuildOptions) { b.Dialer = dialer }) } ================================================ FILE: go/net/resolver/build_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver // A ResolverBuildOption sets options. type ResolverBuildOption interface { apply(*ResolverBuildOptions) } // EmptyResolverBuildUrlOption does not alter the ResolverBuilduration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyResolverBuildOption struct{} func (EmptyResolverBuildOption) apply(*ResolverBuildOptions) {} // ResolverBuildOptionFunc wraps a function that modifies ResolverBuildOptions into an // implementation of the ResolverBuildOption interface. type ResolverBuildOptionFunc func(*ResolverBuildOptions) func (f ResolverBuildOptionFunc) apply(do *ResolverBuildOptions) { f(do) } // sample code for option, default for nothing to change func _ResolverBuildOptionWithDefault() ResolverBuildOption { return ResolverBuildOptionFunc(func(*ResolverBuildOptions) { // nothing to change }) } func (o *ResolverBuildOptions) ApplyOptions(options ...ResolverBuildOption) *ResolverBuildOptions { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/resolver/dns/dns_resolver.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 dns import ( "context" "fmt" "net" "strconv" "sync" "time" rand_ "github.com/kaydxh/golang/go/math/rand" net_ "github.com/kaydxh/golang/go/net" "github.com/kaydxh/golang/go/net/resolver" time_ "github.com/kaydxh/golang/go/time" ) // EnableSRVLookups controls whether the DNS resolver attempts to fetch gRPCLB // addresses from SRV records. Must not be changed after init time. var EnableSRVLookups = false // Globals to stub out in tests. TODO: Perhaps these two can be combined into a // single variable for testing the resolver? var ( newTimer = time.NewTimer ) func init() { resolver.Register(NewBuilder()) } const ( defaultPort = "443" defaultDNSSvrPort = "53" ) var ( defaultResolver netResolver = net.DefaultResolver // To prevent excessive re-resolution, we enforce a rate limit on DNS // resolution requests. defaultSyncInterval = 30 * time.Second ) var customAuthorityDialler = func(authority string) func(ctx context.Context, network, address string) (net.Conn, error) { return func(ctx context.Context, network, address string) (net.Conn, error) { var dialer net.Dialer return dialer.DialContext(ctx, network, authority) } } var customAuthorityResolver = func(authority string) (netResolver, error) { host, port, err := net_.ParseTarget(authority, defaultDNSSvrPort) if err != nil { return nil, err } authorityWithPort := net.JoinHostPort(host, port) return &net.Resolver{ PreferGo: true, Dial: customAuthorityDialler(authorityWithPort), }, nil } // NewBuilder creates a dnsBuilder which is used to factory DNS resolvers. func NewBuilder(opts ...dnsBuilderOption) resolver.Builder { b := &dnsBuilder{} b.ApplyOptions(opts...) if b.opts.syncInterval == 0 { b.opts.syncInterval = defaultSyncInterval } return b } type dnsBuilder struct { opts struct { syncInterval time.Duration } } // Build creates and starts a DNS resolver that watches the name resolution of the target. func (b *dnsBuilder) Build(target resolver.Target, opts ...resolver.ResolverBuildOption) (resolver.Resolver, error) { var opt resolver.ResolverBuildOptions opt.ApplyOptions(opts...) host, port, err := net_.ParseTarget(target.Endpoint, defaultPort) if err != nil { return nil, err } cc := opt.Cc // IP address. if ipAddr, ok := formatIP(host); ok { addr := []resolver.Address{{Addr: ipAddr + ":" + port}} if cc != nil { cc.UpdateState(resolver.State{Addresses: addr}) } return deadResolver{ addrs: addr, }, nil } // DNS address (non-IP). ctx, cancel := context.WithCancel(context.Background()) d := &dnsResolver{ host: host, port: port, syncInterval: b.opts.syncInterval, ctx: ctx, cancel: cancel, cc: cc, rn: make(chan struct{}, 1), } if target.Authority == "" { d.resolver = defaultResolver } else { d.resolver, err = customAuthorityResolver(target.Authority) if err != nil { return nil, err } } d.wg.Add(1) go d.watcher() return d, nil } // Scheme returns the naming scheme of this resolver builder, which is "dns". func (b *dnsBuilder) Scheme() string { return "dns" } type netResolver interface { LookupHost(ctx context.Context, host string) (addrs []string, err error) LookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*net.SRV, err error) LookupTXT(ctx context.Context, name string) (txts []string, err error) } // deadResolver is a resolver that does nothing. type deadResolver struct { addrs []resolver.Address } func (d deadResolver) ResolveOne(opts ...resolver.ResolveOneOption) (resolver.Address, error) { var opt resolver.ResolveOneOptions opt.ApplyOptions(opts...) addrs, err := d.ResolveAll(resolver.WithIPTypeForResolveAll(opt.IPType)) if err != nil { return resolver.Address{}, err } switch opt.PickMode { case resolver.Resolver_pick_mode_random: return addrs[rand_.Intn(len(addrs))], nil case resolver.Resolver_pick_mode_first: return addrs[0], nil default: return addrs[rand_.Intn(len(addrs))], nil } } func (d deadResolver) ResolveAll(opts ...resolver.ResolveAllOption) ([]resolver.Address, error) { var opt resolver.ResolveAllOptions opt.ApplyOptions(opts...) if len(d.addrs) == 0 { return nil, fmt.Errorf("resolve target's addresses are empty") } var pickAddrs []resolver.Address if opt.IPType == resolver.Resolver_ip_type_all { pickAddrs = d.addrs } else { for _, addr := range d.addrs { v4 := (opt.IPType == resolver.Resolver_ip_type_v4) ip, _, _ := net_.SplitHostIntPort(addr.Addr) if net_.IsIPv4String(ip) { if v4 { pickAddrs = append(pickAddrs, addr) } } else { //v6 if !v4 { pickAddrs = append(pickAddrs, addr) } } } } if len(pickAddrs) == 0 { return nil, fmt.Errorf("resolve target's addresses type[%v] are empty", opt.IPType) } return pickAddrs, nil } func (deadResolver) ResolveNow(opts ...resolver.ResolveNowOption) {} func (deadResolver) Close() {} // dnsResolver watches for the name resolution update for a non-IP target. type dnsResolver struct { host string port string resolver netResolver syncInterval time.Duration ctx context.Context cancel context.CancelFunc cc resolver.ClientConn // rn channel is used by ResolveNow() to force an immediate resolution of the target. rn chan struct{} // wg is used to enforce Close() to return after the watcher() goroutine has finished. // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we // replace the real lookup functions with mocked ones to facilitate testing. // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes // will warns lookup (READ the lookup function pointers) inside watcher() goroutine // has data race with replaceNetFunc (WRITE the lookup function pointers). wg sync.WaitGroup } func (d *dnsResolver) ResolveOne(opts ...resolver.ResolveOneOption) (resolver.Address, error) { var opt resolver.ResolveOneOptions opt.ApplyOptions(opts...) addrs, err := d.ResolveAll(resolver.WithIPTypeForResolveAll(opt.IPType)) if err != nil { return resolver.Address{}, err } switch opt.PickMode { case resolver.Resolver_pick_mode_random: return addrs[rand_.Intn(len(addrs))], nil case resolver.Resolver_pick_mode_first: return addrs[0], nil default: return addrs[rand_.Intn(len(addrs))], nil } } func (d *dnsResolver) ResolveAll(opts ...resolver.ResolveAllOption) ([]resolver.Address, error) { var opt resolver.ResolveAllOptions opt.ApplyOptions(opts...) d.ResolveNow() addrs, err := d.lookupHost() if err != nil { return nil, err } if len(addrs) == 0 { return nil, fmt.Errorf("resolve target's addresses are empty") } var pickAddrs []resolver.Address if opt.IPType == resolver.Resolver_ip_type_all { pickAddrs = addrs } else { for _, addr := range addrs { v4 := (opt.IPType == resolver.Resolver_ip_type_v4) ip, _, _ := net_.SplitHostIntPort(addr.Addr) if net_.IsIPv4String(ip) { if v4 { pickAddrs = append(pickAddrs, addr) } } else { //v6 if !v4 { pickAddrs = append(pickAddrs, addr) } } } } if len(pickAddrs) == 0 { return nil, fmt.Errorf("resolve target's addresses type[%v] are empty", opt.IPType) } return pickAddrs, nil } // ResolveNow invoke an immediate resolution of the target that this dnsResolver watches. func (d *dnsResolver) ResolveNow(opts ...resolver.ResolveNowOption) { select { case d.rn <- struct{}{}: default: } } // Close closes the dnsResolver. func (d *dnsResolver) Close() { d.cancel() d.wg.Wait() } func (d *dnsResolver) watcher() { defer d.wg.Done() backoff := time_.NewExponentialBackOff() for { addrs, err := d.lookupHost() if d.cc != nil { if err != nil { // Report error to the underlying grpc.ClientConn. d.cc.ReportError(err) } else { err = d.cc.UpdateState(resolver.State{Addresses: addrs}) } } var timer *time.Timer if err == nil { // Success resolving, wait for the next ResolveNow. However, also wait 30 seconds at the very least // to prevent constantly re-resolving. backoff.Reset() timer = newTimer(d.syncInterval) select { case <-d.ctx.Done(): timer.Stop() return case <-d.rn: } } else { // Poll on an error found in DNS Resolver or an error received from ClientConn. actualInterval, _ := backoff.NextBackOff() timer = newTimer(actualInterval) } select { case <-d.ctx.Done(): timer.Stop() return case <-timer.C: } } } func (d *dnsResolver) lookupSRV() ([]resolver.Address, error) { if !EnableSRVLookups { return nil, nil } var newAddrs []resolver.Address _, srvs, err := d.resolver.LookupSRV(d.ctx, "grpclb", "tcp", d.host) if err != nil { err = handleDNSError(err, "SRV") // may become nil return nil, err } for _, s := range srvs { lbAddrs, err := d.resolver.LookupHost(d.ctx, s.Target) if err != nil { err = handleDNSError(err, "A") // may become nil if err == nil { // If there are other SRV records, look them up and ignore this // one that does not exist. continue } return nil, err } for _, a := range lbAddrs { ip, ok := formatIP(a) if !ok { return nil, fmt.Errorf("dns: error parsing A record IP address %v", a) } addr := ip + ":" + strconv.Itoa(int(s.Port)) newAddrs = append(newAddrs, resolver.Address{Addr: addr, ServerName: s.Target}) } } return newAddrs, nil } func handleDNSError(err error, lookupType string) error { if dnsErr, ok := err.(*net.DNSError); ok && !dnsErr.IsTimeout && !dnsErr.IsTemporary { // Timeouts and temporary errors should be communicated to gRPC to // attempt another DNS query (with backoff). Other errors should be // suppressed (they may represent the absence of a TXT record). return nil } if err != nil { err = fmt.Errorf("dns: %v record lookup error: %v", lookupType, err) } return err } func (d *dnsResolver) lookupHost() ([]resolver.Address, error) { addrs, err := d.resolver.LookupHost(d.ctx, d.host) if err != nil { err = handleDNSError(err, "A") return nil, err } newAddrs := make([]resolver.Address, 0, len(addrs)) for _, a := range addrs { ip, ok := formatIP(a) if !ok { return nil, fmt.Errorf("dns: error parsing A record IP address %v", a) } addr := ip + ":" + d.port newAddrs = append(newAddrs, resolver.Address{Addr: addr}) } return newAddrs, nil } // formatIP returns ok = false if addr is not a valid textual representation of an IP address. // If addr is an IPv4 address, return the addr and ok = true. // If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true. func formatIP(addr string) (addrIP string, ok bool) { ip := net.ParseIP(addr) if ip == nil { return "", false } if ip.To4() != nil { return addr, true } return "[" + addr + "]", true } ================================================ FILE: go/net/resolver/dns/dns_resolver_builder.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 dns import ( "time" ) func WithSyncInterval(syncInterval time.Duration) dnsBuilderOption { return dnsBuilderOptionFunc(func(c *dnsBuilder) { c.opts.syncInterval = syncInterval }) } ================================================ FILE: go/net/resolver/dns/dns_resolver_builder_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 dns // A dnsBuilderOption sets options. type dnsBuilderOption interface { apply(*dnsBuilder) } // EmptydnsBuilderUrlOption does not alter the dnsBuilderuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptydnsBuilderOption struct{} func (EmptydnsBuilderOption) apply(*dnsBuilder) {} // dnsBuilderOptionFunc wraps a function that modifies dnsBuilder into an // implementation of the dnsBuilderOption interface. type dnsBuilderOptionFunc func(*dnsBuilder) func (f dnsBuilderOptionFunc) apply(do *dnsBuilder) { f(do) } // sample code for option, default for nothing to change func _dnsBuilderOptionWithDefault() dnsBuilderOption { return dnsBuilderOptionFunc(func(*dnsBuilder) { // nothing to change }) } func (o *dnsBuilder) ApplyOptions(options ...dnsBuilderOption) *dnsBuilder { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/resolver/passthrough/passthrough.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 passthrough import ( "github.com/kaydxh/golang/go/net/resolver" ) const scheme = "passthrough" type passthroughBuilder struct{} func (*passthroughBuilder) Build(target resolver.Target, opts ...resolver.ResolverBuildOption) (resolver.Resolver, error) { var opt resolver.ResolverBuildOptions opt.ApplyOptions(opts...) r := &passthroughResolver{ target: target, } return r, nil } func (*passthroughBuilder) Scheme() string { return scheme } type passthroughResolver struct { target resolver.Target } func (r *passthroughResolver) ResolveOne(opts ...resolver.ResolveOneOption) (resolver.Address, error) { return resolver.Address{Addr: r.target.Endpoint}, nil } func (r *passthroughResolver) ResolveAll(opts ...resolver.ResolveAllOption) ([]resolver.Address, error) { return []resolver.Address{{Addr: r.target.Endpoint}}, nil } func (r *passthroughResolver) ResolveNow(opts ...resolver.ResolveNowOption) {} func (*passthroughResolver) Close() {} func init() { resolver.Register(&passthroughBuilder{}) } ================================================ FILE: go/net/resolver/register.reslover.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver import "sync" var ( builderMu sync.RWMutex resolversMu sync.RWMutex // m is a map from scheme to resolver builder. m = make(map[string]Builder) resolverPool = make(map[string]Resolver) // defaultScheme is the default scheme to use. defaultScheme = "passthrough" ) // TODO(bar) install dns resolver in init(){}. // Register registers the resolver builder to the resolver map. b.Scheme will be // used as the scheme registered with this builder. // func Register(b Builder) { builderMu.Lock() defer builderMu.Unlock() if b == nil { panic("register builder is nil") } if _, ok := m[b.Scheme()]; ok { panic("double register scheme " + b.Scheme()) } m[b.Scheme()] = b } // Get returns the resolver builder registered with the given scheme. // // If no builder is register with the scheme, nil will be returned. func Get(scheme string) Builder { builderMu.Lock() defer builderMu.Unlock() if b, ok := m[scheme]; ok { return b } return nil } func GetDefault() Builder { builderMu.Lock() defer builderMu.Unlock() if b, ok := m[defaultScheme]; ok { return b } return nil } func getResolver(target string) Resolver { resolversMu.Lock() defer resolversMu.Unlock() if b, ok := resolverPool[target]; ok { return b } return nil } func setResolver(target string, r Resolver) { resolversMu.Lock() defer resolversMu.Unlock() if r == nil { panic("register resolver is nil") } if _, ok := resolverPool[target]; ok { panic("double register target " + target) } resolverPool[target] = r } // SetDefaultScheme sets the default scheme that will be used. The default // default scheme is "passthrough". // // NOTE: this function must only be called during initialization time (i.e. in // an init() function), and is not thread-safe. The scheme set last overrides // previously set values. func SetDefaultScheme(scheme string) { defaultScheme = scheme } // GetDefaultScheme gets the default scheme that will be used. func GetDefaultScheme() string { return defaultScheme } ================================================ FILE: go/net/resolver/resolve/resolve.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolve import ( "context" "github.com/kaydxh/golang/go/net/resolver" _ "github.com/kaydxh/golang/go/net/resolver/dns" _ "github.com/kaydxh/golang/go/net/resolver/passthrough" _ "github.com/kaydxh/golang/go/net/resolver/unix" ) func ResolveOne(ctx context.Context, target string, opts ...resolver.ResolveOneOption) (resolver.Address, error) { r, err := resolver.GetResolver(ctx, target) if err != nil { return resolver.Address{}, err } return r.ResolveOne(opts...) } func ResolveAll(ctx context.Context, target string, opts ...resolver.ResolveAllOption) ([]resolver.Address, error) { r, err := resolver.GetResolver(ctx, target) if err != nil { return nil, err } return r.ResolveAll(opts...) } ================================================ FILE: go/net/resolver/resolve.all.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver func WithIPTypeForResolveAll(ipType Resolver_IPType) ResolveAllOptionFunc { return ResolveAllOptionFunc(func(r *ResolveAllOptions) { r.IPType = ipType }) } ================================================ FILE: go/net/resolver/resolve.all_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver // A ResolveAllOption sets options. type ResolveAllOption interface { apply(*ResolveAllOptions) } // EmptyResolveAllUrlOption does not alter the ResolveAlluration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyResolveAllOption struct{} func (EmptyResolveAllOption) apply(*ResolveAllOptions) {} // ResolveAllOptionFunc wraps a function that modifies ResolveAllOptions into an // implementation of the ResolveAllOption interface. type ResolveAllOptionFunc func(*ResolveAllOptions) func (f ResolveAllOptionFunc) apply(do *ResolveAllOptions) { f(do) } // sample code for option, default for nothing to change func _ResolveAllOptionWithDefault() ResolveAllOption { return ResolveAllOptionFunc(func(*ResolveAllOptions) { // nothing to change }) } func (o *ResolveAllOptions) ApplyOptions(options ...ResolveAllOption) *ResolveAllOptions { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/resolver/resolve.now_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver // A ResolveNowOption sets options. type ResolveNowOption interface { apply(*ResolveNowOptions) } // EmptyResolveNowUrlOption does not alter the ResolveNowuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyResolveNowOption struct{} func (EmptyResolveNowOption) apply(*ResolveNowOptions) {} // ResolveNowOptionFunc wraps a function that modifies ResolveNowOptions into an // implementation of the ResolveNowOption interface. type ResolveNowOptionFunc func(*ResolveNowOptions) func (f ResolveNowOptionFunc) apply(do *ResolveNowOptions) { f(do) } // sample code for option, default for nothing to change func _ResolveNowOptionWithDefault() ResolveNowOption { return ResolveNowOptionFunc(func(*ResolveNowOptions) { // nothing to change }) } func (o *ResolveNowOptions) ApplyOptions(options ...ResolveNowOption) *ResolveNowOptions { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/resolver/resolve.one.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver func WithPickMode(mode Resolver_PickMode) ResolveOneOptionFunc { return ResolveOneOptionFunc(func(r *ResolveOneOptions) { r.PickMode = mode }) } func WithIPTypeForResolverOne(ipType Resolver_IPType) ResolveOneOptionFunc { return ResolveOneOptionFunc(func(r *ResolveOneOptions) { r.IPType = ipType }) } ================================================ FILE: go/net/resolver/resolve.one_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver // A ResolveOneOption sets options. type ResolveOneOption interface { apply(*ResolveOneOptions) } // EmptyResolveOneUrlOption does not alter the ResolveOneuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyResolveOneOption struct{} func (EmptyResolveOneOption) apply(*ResolveOneOptions) {} // ResolveOneOptionFunc wraps a function that modifies ResolveOneOptions into an // implementation of the ResolveOneOption interface. type ResolveOneOptionFunc func(*ResolveOneOptions) func (f ResolveOneOptionFunc) apply(do *ResolveOneOptions) { f(do) } // sample code for option, default for nothing to change func _ResolveOneOptionWithDefault() ResolveOneOption { return ResolveOneOptionFunc(func(*ResolveOneOptions) { // nothing to change }) } func (o *ResolveOneOptions) ApplyOptions(options ...ResolveOneOption) *ResolveOneOptions { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/resolver/resolver.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver import ( "fmt" "context" ) // ResolveNowOptions includes additional information for ResolveNow. type ResolveNowOptions struct{} // Resolver watches for the updates on the specified target. // Updates include address updates and service config updates. type Resolver interface { // It could be called multiple times concurrently. ResolveOne(opts ...ResolveOneOption) (Address, error) ResolveAll(opts ...ResolveAllOption) ([]Address, error) // ResolveNow will be called by gRPC to try to resolve the target name // again. It's just a hint, resolver can ignore this if it's not necessary. // // It could be called multiple times concurrently. ResolveNow(opts ...ResolveNowOption) // Close closes the resolver. Close() } type Resolver_PickMode int32 const ( Resolver_pick_mode_random Resolver_PickMode = 0 Resolver_pick_mode_first Resolver_PickMode = 1 ) type Resolver_IPType int32 const ( Resolver_ip_type_all Resolver_IPType = 0 Resolver_ip_type_v4 Resolver_IPType = 1 Resolver_ip_type_v6 Resolver_IPType = 2 ) type ResolveOneOptions struct { PickMode Resolver_PickMode IPType Resolver_IPType } type ResolveAllOptions struct { IPType Resolver_IPType } func GetResolver(ctx context.Context, target string, opts ...ResolverBuildOption) (Resolver, error) { var opt ResolverBuildOptions opt.ApplyOptions(opts...) targetInfo, err := ParseTarget(target) if err != nil { // support no scheme, just ip:port format if targetInfo.Scheme == "" { return GetDefault().Build(Target{ Endpoint: target, }) } return nil, fmt.Errorf("target[%v] is invalid", targetInfo) } r := getResolver(target) if r == nil { builder := Get(targetInfo.Scheme) if builder == nil { return nil, fmt.Errorf("scheme[%v] was not registered", targetInfo.Scheme) } r, err = builder.Build(targetInfo) if err != nil { return nil, fmt.Errorf("failed to build target[%v], err: %v", targetInfo, err) } setResolver(target, r) } return r, nil } ================================================ FILE: go/net/resolver/resolver_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver_test import ( "fmt" "testing" "context" "github.com/kaydxh/golang/go/net/resolver" resolver_ "github.com/kaydxh/golang/go/net/resolver" _ "github.com/kaydxh/golang/go/net/resolver/dns" _ "github.com/kaydxh/golang/go/net/resolver/passthrough" resolve_ "github.com/kaydxh/golang/go/net/resolver/resolve" ) func TestResolveOne(t *testing.T) { testCases := []struct { target string iptype resolver.Resolver_IPType expected string }{ { target: "dns:///www.baidu.com:10000", iptype: resolver.Resolver_ip_type_v4, expected: "", }, { target: "dns:///www.google.com", iptype: resolver.Resolver_ip_type_v4, expected: "", }, { target: "dns:///198.121.11.1", iptype: resolver.Resolver_ip_type_v4, expected: "", }, { target: "passthrough:///198.121.11.2", iptype: resolver.Resolver_ip_type_v4, expected: "", }, { target: "198.121.11.2", iptype: resolver.Resolver_ip_type_v4, expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d-test", i), func(t *testing.T) { addr, err := resolve_.ResolveOne(context.Background(), testCase.target, resolver_.WithPickMode(resolver_.Resolver_pick_mode_first)) if err != nil { t.Fatalf("failed to resolve target: %v, err: %v", testCase.target, err) } t.Logf("resolve one addr %v for target %v", addr, testCase.target) }) } } func TestResolveAll(t *testing.T) { testCases := []struct { target string iptype resolver.Resolver_IPType expected string }{ { target: "dns:///www.baidu.com", iptype: resolver.Resolver_ip_type_v4, expected: "", }, { target: "dns:///www.google.com", iptype: resolver.Resolver_ip_type_v4, expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d-test", i), func(t *testing.T) { addrs, err := resolve_.ResolveAll(context.Background(), testCase.target, resolver.WithIPTypeForResolveAll(testCase.iptype)) if err != nil { t.Fatalf("failed to resolve target: %v, err: %v", testCase.target, err) } t.Logf("resolve all addrs %v for target %v", addrs, testCase.target) }) } } ================================================ FILE: go/net/resolver/target.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 resolver import ( "net/url" "strings" ) // Target represents a target for gRPC, as specified in: // https://github.com/grpc/grpc/blob/master/doc/naming.md. // It is parsed from the target string that gets passed into Dial or DialContext by the user. And // grpc passes it to the resolver and the balancer. // // If the target follows the naming spec, and the parsed scheme is registered with grpc, we will // parse the target string according to the spec. e.g. "dns://some_authority/foo.bar" will be parsed // into &Target{Scheme: "dns", Authority: "some_authority", Endpoint: "foo.bar"} // // If the target does not contain a scheme, we will apply the default scheme, and set the Target to // be the full target string. e.g. "foo.bar" will be parsed into // &Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "foo.bar"}. // // If the parsed scheme is not registered (i.e. no corresponding resolver available to resolve the // endpoint), we set the Scheme to be the default scheme, and set the Endpoint to be the full target // string. e.g. target string "unknown_scheme://authority/endpoint" will be parsed into // &Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "unknown_scheme://authority/endpoint"}. type Target struct { Scheme string Authority string Endpoint string URL url.URL } // parseTarget uses RFC 3986 semantics to parse the given target into a // resolver.Target struct containing scheme, authority and endpoint. Query // params are stripped from the endpoint. // use URL first func ParseTarget(target string) (Target, error) { u, err := url.Parse(target) if err != nil { return Target{}, err } // For targets of the form "[scheme]://[authority]/endpoint, the endpoint // value returned from url.Parse() contains a leading "/". Although this is // in accordance with RFC 3986, we do not want to break existing resolver // implementations which expect the endpoint without the leading "/". So, we // end up stripping the leading "/" here. But this will result in an // incorrect parsing for something like "unix:///path/to/socket". Since we // own the "unix" resolver, we can workaround in the unix resolver by using // the `URL` field instead of the `Endpoint` field. endpoint := u.Path if endpoint == "" { endpoint = u.Opaque } endpoint = strings.TrimPrefix(endpoint, "/") return Target{ Scheme: u.Scheme, Authority: u.Host, Endpoint: endpoint, URL: *u, }, nil } // ParseTarget splits target into a resolver.Target struct containing scheme, // authority and endpoint. skipUnixColonParsing indicates that the parse should // not parse "unix:[path]" cases. This should be true in cases where a custom // dialer is present, to prevent a behavior change. // // If target is not a valid scheme://authority/endpoint as specified in // https://github.com/grpc/grpc/blob/master/doc/naming.md, // it returns {Endpoint: target}. /* func ParseTarget(target string, skipUnixColonParsing bool) (ret Target) { var ok bool if strings.HasPrefix(target, "unix-abstract:") { if strings.HasPrefix(target, "unix-abstract://") { // Maybe, with Authority specified, try to parse it var remain string ret.Scheme, remain, _ = strings_.Split2(target, "://") ret.Authority, ret.Endpoint, ok = strings_.Split2(remain, "/") if !ok { // No Authority, add the "//" back ret.Endpoint = "//" + remain } else { // Found Authority, add the "/" back ret.Endpoint = "/" + ret.Endpoint } } else { // Without Authority specified, split target on ":" ret.Scheme, ret.Endpoint, _ = strings_.Split2(target, ":") } return ret } ret.Scheme, ret.Endpoint, ok = strings_.Split2(target, "://") if !ok { if strings.HasPrefix(target, "unix:") && !skipUnixColonParsing { // Handle the "unix:[local/path]" and "unix:[/absolute/path]" cases, // because splitting on :// only handles the // "unix://[/absolute/path]" case. Only handle if the dialer is nil, // to avoid a behavior change with custom dialers. return Target{Scheme: "unix", Endpoint: target[len("unix:"):]} } return Target{Endpoint: target} } ret.Authority, ret.Endpoint, ok = strings_.Split2(ret.Endpoint, "/") if !ok { return Target{Endpoint: target} } if ret.Scheme == "unix" { // Add the "/" back in the unix case, so the unix resolver receives the // actual endpoint in the "unix://[/absolute/path]" case. ret.Endpoint = "/" + ret.Endpoint } return ret } */ ================================================ FILE: go/net/resolver/unix/unix.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 unix import ( "fmt" "github.com/kaydxh/golang/go/net/resolver" ) const unixScheme = "unix" const unixAbstractScheme = "unix-abstract" type builder struct { scheme string } func (b *builder) Build(target resolver.Target, opts ...resolver.ResolverBuildOption) (resolver.Resolver, error) { if target.Authority != "" { return nil, fmt.Errorf("invalid (non-empty) authority: %v", target.Authority) } var opt resolver.ResolverBuildOptions opt.ApplyOptions(opts...) addr := resolver.Address{Addr: target.Endpoint} if b.scheme == unixAbstractScheme { // prepend "\x00" to address for unix-abstract addr.Addr = "\x00" + addr.Addr } cc := opt.Cc if cc != nil { cc.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: addr.Addr}}}) } return &nopResolver{addrs: []resolver.Address{{Addr: addr.Addr}}}, nil } func (b *builder) Scheme() string { return b.scheme } type nopResolver struct { addrs []resolver.Address } func (*nopResolver) ResolveOne(opts ...resolver.ResolveOneOption) (resolver.Address, error) { return resolver.Address{}, nil } func (*nopResolver) ResolveAll(opts ...resolver.ResolveAllOption) ([]resolver.Address, error) { return nil, nil } func (*nopResolver) ResolveNow(opts ...resolver.ResolveNowOption) {} func (*nopResolver) Close() {} func init() { resolver.Register(&builder{scheme: unixScheme}) resolver.Register(&builder{scheme: unixAbstractScheme}) } ================================================ FILE: go/net/url/url.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 url import ( "bytes" "context" "fmt" "reflect" "strconv" "sync" ) type Client struct { mutex sync.Mutex buffer *bytes.Buffer opts struct { needEmptyValue bool urlCodec UrlCodec } } func New(ctx context.Context, options ...ClientOption) (*Client, error) { c := &Client{} c.opts.urlCodec = DefaultUrlCodec{} c.ApplyOptions(options...) return c, nil } //can convert struct to url encode for url paratment func (c *Client) Encode(data interface{}) (string, error) { c.mutex.Lock() defer c.mutex.Unlock() c.buffer = new(bytes.Buffer) rv := reflect.ValueOf(data) err := c.build(rv, "", reflect.Interface) if err != nil { return "", err } buf := c.buffer.Bytes() c.buffer = nil return string(buf[0 : len(buf)-1]), nil } func (c *Client) encode(rv reflect.Value) (string, error) { encoder := getEncoder(rv.Kind()) if encoder == nil { return "", fmt.Errorf("unsupport type: %v", rv.Type().String()) } return encoder.Encode(rv), nil } func (c *Client) build( rv reflect.Value, parentKey string, parentKind reflect.Kind, ) error { fmt.Println("-- parentKey: ", parentKey) switch rv.Kind() { case reflect.Map: for _, key := range rv.MapKeys() { checkKey := key if key.Kind() == reflect.Interface || key.Kind() == reflect.Ptr { checkKey = checkKey.Elem() } keyStr, err := c.encode(checkKey) if err != nil { return err } c.build(rv.MapIndex(key), keyStr, rv.Kind()) } case reflect.Slice, reflect.Array: for i := 0; i < rv.Len(); i++ { c.build(rv.Index(i), parentKey+"["+strconv.Itoa(i)+"]", rv.Kind()) } case reflect.Struct: rt := rv.Type() for i := 0; i < rt.NumField(); i++ { ft := rt.Field(i) //unexported if ft.PkgPath != "" && !ft.Anonymous { continue } //specially handle anonymous fields if ft.Anonymous && rv.Field(i).Kind() == reflect.Struct { c.build(rv.Field(i), parentKey, rv.Kind()) continue } /* tag := ft.Tag.Get("query") //all ignore if tag == "-" { continue } t := newTag(tag) //get the related name name := t.getName() if name == "" { name = ft.Name } */ name := ft.Name c.build(rv.Field(i), name, rv.Kind()) } case reflect.Ptr, reflect.Interface: if !rv.IsNil() { c.build(rv.Elem(), parentKey, parentKind) } default: c.appendKeyValue(parentKey, rv, parentKind) } return nil } //basic structure can be translated directly func (c *Client) appendKeyValue(key string, rv reflect.Value, parentKind reflect.Kind) error { //If parent type is struct and empty value will be ignored by default. unless needEmptyValue is true. if parentKind == reflect.Struct && !c.opts.needEmptyValue && isEmptyValue(rv) { return nil } //If parent type is slice or array, then repack key. eg. students[0] -> students[] if parentKind == reflect.Slice || parentKind == reflect.Array { key = repackArrayQueryKey(key) } s, err := c.encode(rv) if err != nil { return err } _, err = c.buffer.WriteString( c.opts.urlCodec.Escape(key) + "=" + c.opts.urlCodec.Escape(s) + "&", ) return err } //Is Zero-value func isEmptyValue(v reflect.Value) bool { switch v.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: return v.Len() == 0 case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Ptr: return v.IsNil() } return false } //if key like `students[0]` , repack it to `students[]` func repackArrayQueryKey(key string) string { l := len(key) if l > 0 && key[l-1] == ']' { for l--; l >= 0; l-- { if key[l] == '[' { return key[:l+1] + "]" } } } return key } ================================================ FILE: go/net/url/url.resolve.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 url import ( "context" "net/url" resolve_ "github.com/kaydxh/golang/go/net/resolver/resolve" ) func ResolveWithTarget(ctx context.Context, u *url.URL, target string) (*url.URL, error) { if u == nil { return nil, nil } newUrl := u if target == "" { return newUrl, nil } addr, err := resolve_.ResolveOne(ctx, target) if err != nil { return nil, err } newUrl.Host = addr.Addr return newUrl, nil } ================================================ FILE: go/net/url/url_codec.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 url import "net/url" type UrlCodec interface { Escape(s string) string UnEscape(s string) (string, error) } //default url codec type DefaultUrlCodec struct{} func (u DefaultUrlCodec) Escape(s string) string { return url.QueryEscape(s) } func (u DefaultUrlCodec) UnEscape(s string) (string, error) { return url.QueryUnescape(s) } ================================================ FILE: go/net/url/url_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 url // A ClientOption sets options. type ClientOption interface { apply(*Client) } // EmptyClientOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyClientOption struct{} func (EmptyClientOption) apply(*Client) {} // ClientOptionFunc wraps a function that modifies Client into an // implementation of the ClientOption interface. type ClientOptionFunc func(*Client) func (f ClientOptionFunc) apply(do *Client) { f(do) } // sample code for option, default for nothing to change func _ClientOptionWithDefault() ClientOption { return ClientOptionFunc(func(*Client) { // nothing to change }) } func (o *Client) ApplyOptions(options ...ClientOption) *Client { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/net/url/url_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 url_test import ( "fmt" "testing" url_ "github.com/kaydxh/golang/go/net/url" "golang.org/x/net/context" ) func TestUrlEncode(t *testing.T) { type SimpleChild struct { Status bool Name string } type SimpleData struct { Id int Name string Child SimpleChild ParamsInt8 map[string]int8 ParamsString map[string]string Array [3]uint16 } data := SimpleData{ Id: 2, Name: "http://localhost/test.php?id=2", Child: SimpleChild{ Status: true, }, ParamsInt8: map[string]int8{ "one": 1, }, ParamsString: map[string]string{ "two": "你好", }, Array: [3]uint16{2, 3, 300}, } c, _ := url_.New(context.Background()) bytes, err := c.Encode(data) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println(string(bytes)) } ================================================ FILE: go/net/url/value.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 url import ( "reflect" "strconv" ) var ( boolV = boolValue{} intV = intValue{} unitV = uintValue{} floatV = floatValue{} stringV = stringValue{} encoderMap = map[reflect.Kind]Value{ reflect.Bool: boolV, reflect.Int: intV, reflect.Int8: intV, reflect.Int16: intV, reflect.Int32: intV, reflect.Int64: intV, reflect.Uint: unitV, reflect.Uint8: unitV, reflect.Uint16: unitV, reflect.Uint32: unitV, reflect.Uint64: unitV, reflect.Uintptr: unitV, reflect.Float32: floatV, reflect.Float64: floatV, reflect.String: stringV, } ) type Value interface { Encode(value reflect.Value) string //Decode(value string) (reflect.Value, error) } type boolValue struct{} func (e boolValue) Encode(value reflect.Value) string { if value.Bool() { return "1" } return "0" } type intValue struct{} func (e intValue) Encode(value reflect.Value) string { return strconv.FormatInt(value.Int(), 10) } type uintValue struct{} func (e uintValue) Encode(value reflect.Value) string { return strconv.FormatUint(value.Uint(), 10) } type floatValue struct{} func (e floatValue) Encode(value reflect.Value) string { return strconv.FormatFloat(value.Float(), 'f', -1, 64) } type stringValue struct{} func (e stringValue) Encode(value reflect.Value) string { return value.String() } func getEncoder(kind reflect.Kind) Value { if encoder, ok := encoderMap[kind]; ok { return encoder } return nil } ================================================ FILE: go/os/env.go ================================================ /* MIT License Copyright (c) 2020 kay 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 os import ( "os" "strconv" ) // GetEnvAsStringOrFallback returns the env variable for the given key // and falls back to the given defaultValue if not set func GetEnvAsStringOrFallback(key, defaultValue string) string { if v := os.Getenv(key); v != "" { return v } return defaultValue } // GetEnvAsIntOrFallback returns the env variable (parsed as integer) for // the given key and falls back to the given defaultValue if not set func GetEnvAsIntOrFallback(key string, defaultValue int) (int, error) { if v := os.Getenv(key); v != "" { value, err := strconv.Atoi(v) if err != nil { return defaultValue, err } return value, nil } return defaultValue, nil } // GetEnvAsFloat64OrFallback returns the env variable (parsed as float64) for // the given key and falls back to the given defaultValue if not set func GetEnvAsFloat64OrFallback(key string, defaultValue float64) (float64, error) { if v := os.Getenv(key); v != "" { value, err := strconv.ParseFloat(v, 64) if err != nil { return defaultValue, err } return value, nil } return defaultValue, nil } ================================================ FILE: go/os/env_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os_test import ( "os" "testing" "github.com/google/uuid" os_ "github.com/kaydxh/golang/go/os" "github.com/stretchr/testify/assert" ) func TestGetEnvAsStringOrFallback(t *testing.T) { const expected = "foo" assert := assert.New(t) key := "FLOCKER_SET_VAR" os.Setenv(key, expected) assert.Equal(expected, os_.GetEnvAsStringOrFallback(key, "~"+expected)) key = "FLOCKER_UNSET_VAR" assert.Equal(expected, os_.GetEnvAsStringOrFallback(key, expected)) assert.NotEqual(expected, os_.GetEnvAsStringOrFallback(key, "~"+expected)) } //gotests -w -all go/os/env.go //gotests -only GetEnvAsIntOrFallback go/os/env.go func TestUUID(t *testing.T) { id := uuid.New().String() t.Logf("uuid: %v ", id) } func TestGetEnvAsIntOrFallback(t *testing.T) { type args struct { key string defaultValue int } tests := []struct { name string args args want int wantErr bool }{ // TODO: Add test cases. { name: "test1", args: args{ key: "FLOCKER_SET_VAR_INT", defaultValue: 0, }, want: 0, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := os_.GetEnvAsIntOrFallback(tt.args.key, tt.args.defaultValue) if (err != nil) != tt.wantErr { t.Errorf("GetEnvAsIntOrFallback() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { t.Errorf("GetEnvAsIntOrFallback() = %v, want %v", got, tt.want) } }) } } func TestGetEnvAsFloat64OrFallback(t *testing.T) { type args struct { key string defaultValue float64 } tests := []struct { name string args args want float64 wantErr bool }{ // TODO: Add test cases. { name: "test1", args: args{ key: "FLOCKER_SET_VAR_FLOAT", defaultValue: 1.0, }, want: 1.0, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := os_.GetEnvAsFloat64OrFallback(tt.args.key, tt.args.defaultValue) if (err != nil) != tt.wantErr { t.Errorf("GetEnvAsFloat64OrFallback() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { t.Errorf("GetEnvAsFloat64OrFallback() = %v, want %v", got, tt.want) } }) } } ================================================ FILE: go/os/exec/exec.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 exec import ( "bytes" "context" "fmt" "os/exec" "syscall" "time" context_ "github.com/kaydxh/golang/go/context" ) type CommandBuilder struct { cmd exec.Cmd opts struct { Timeout time.Duration } } func NewCommandBuilder( options ...CommandBuilderOption, ) (*CommandBuilder, error) { c := &CommandBuilder{} c.ApplyOptions(options...) return c, nil } // Exec return output result, err messgae, error func (c *CommandBuilder) Exec(cmdName string, args ...string, ) (string, string, error) { return Exec(c.opts.Timeout, cmdName, args...) } //timout ms func Exec( timeout time.Duration, cmdName string, args ...string, ) (string, string, error) { ctx, cancel := context_.WithTimeout( context.Background(), timeout, ) defer cancel() var stdout, stderr bytes.Buffer args = append([]string{"-c", cmdName}, args...) cmd := exec.CommandContext(ctx, "/bin/sh", args...) cmd.Stdout, cmd.Stderr = &stdout, &stderr cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} if err := cmd.Start(); err != nil { return "", "", fmt.Errorf( "error starting %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, cmd.Stdout, cmd.Stderr, err, ) } errCh := make(chan error, 1) go func() { errCh <- cmd.Wait() }() select { case err := <-errCh: if err != nil { var rc = 127 if ee, ok := err.(*exec.ExitError); ok { rc = int(ee.Sys().(syscall.WaitStatus).ExitStatus()) } return stdout.String(), stderr.String(), fmt.Errorf( "error running %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v\ncode:\n%v", cmd, cmd.Stdout, cmd.Stderr, err, rc, ) } case <-ctx.Done(): cmd.Process.Kill() return "", "", fmt.Errorf( "timed out waiting for command %v:\nCommand stdout:\n%v\nstderr:\n%v", cmd, cmd.Stdout, cmd.Stderr, ) } return stdout.String(), stderr.String(), nil } ================================================ FILE: go/os/exec/exec.options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 exec import "time" //timeout func WithTimeout(timeout time.Duration) CommandBuilderOption { return CommandBuilderOptionFunc(func(c *CommandBuilder) { c.opts.Timeout = timeout }) } ================================================ FILE: go/os/exec/exec_options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 exec var _default_CommandBuilder_value = func() (val CommandBuilder) { return }() type CommandBuilderOption interface { apply(*CommandBuilder) } // EmptyCommandBuilderOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyCommandBuilderOption struct{} func (EmptyCommandBuilderOption) apply(*CommandBuilder) {} // CopyDirOptionFunc wraps a function that modifies CopyDir into an // implementation of the CopyDirOption interface. type CommandBuilderOptionFunc func(*CommandBuilder) func (f CommandBuilderOptionFunc) apply(do *CommandBuilder) { f(do) } // sample code for option, default for nothing to change func _CommandBuilderOptionWithDefault() CommandBuilderOption { return CommandBuilderOptionFunc(func(*CommandBuilder) { // nothing to change }) } func (o *CommandBuilder) ApplyOptions( options ...CommandBuilderOption, ) *CommandBuilder { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/os/exec/exec_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 exec_test import ( "fmt" "testing" "time" exec_ "github.com/kaydxh/golang/go/os/exec" ) func TestExec(t *testing.T) { cmd := fmt.Sprintf(`ps -elf`) timeout := 5 * time.Second //ms result, msg, err := exec_.Exec(time.Duration(timeout), cmd) if err != nil { t.Errorf("expect nil, got %v, msg: %v", err, msg) } t.Logf("result: %v", result) } func TestExecTimeout(t *testing.T) { // sleep 2s cmd := fmt.Sprintf(`sleep 2`) timeout := time.Second result, msg, err := exec_.Exec(time.Duration(timeout), cmd) if err != nil { t.Errorf("expect nil, got %v, msg: %v", err, msg) } t.Logf("result: %v", result) } ================================================ FILE: go/os/file.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os import ( "fmt" "os" "path/filepath" "strings" ) func PathExist(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } func IsDir(path string) (bool, error) { fi, err := os.Stat(path) if err != nil { return false, err } return fi.IsDir(), nil } func IsHidden(path string) (bool, error) { _, err := os.Stat(path) if err != nil { return false, err } base := filepath.Base(path) if base == "." || base == ".." { return false, nil } if len(base) > 0 && base[0] == '.' { return true, nil } return false, nil } // MkdirAll creates a directory named path, // along with any necessary parents, and returns nil, // or else returns an error. // The permission(0755) bits perm (before umask) are used for all // directories that MkdirAll creates. // If path is already a directory, MkdirAll does nothing func MakeDirAll(name string) error { return os.MkdirAll(name, 0755) } func MakeDir(name string) error { return os.Mkdir(name, 0755) } // if name is empty, create a directory named name, or creates a new temporary directory in the directory dir // pattern can be empty func MakeTempDirAll(name, pattern string) (string, error) { if name != "" { // make base dir, or if the dir is not exist, MakeTempDirAll return error err := MakeDirAll(name) if err != nil { return "", err } } return os.MkdirTemp(name, pattern) } func OpenAll(path string, flag int, perm os.FileMode) (*os.File, error) { dir, file := filepath.Split(path) // file or dir exists if _, err := os.Stat(path); err == nil { return os.OpenFile(path, flag, perm) } // mkdir -p dir if dir != "" { if err := MakeDirAll(dir); err != nil { return nil, err } } if file == "" { return nil, nil } return os.OpenFile(path, flag, perm) } func OpenFile(path string, appended bool) (file *os.File, err error) { if !appended { file, err = OpenAll(path, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666) } else { file, err = OpenAll(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666) } return file, err } // SameFile reports whether fi1 and fi2 describe the same file. func SameFile(fi1, fi2 string) bool { stat1, err := os.Stat(fi1) if err != nil { return false } stat2, err := os.Stat(fi2) if err != nil { return false } return os.SameFile(stat1, stat2) } // oldname and newname is full path func SymLink(oldname, newname string) error { oldname, err := filepath.Abs(oldname) if err != nil { return err } newname, err = filepath.Abs(newname) if err != nil { return err } _, err = os.Stat(oldname) if err != nil { return fmt.Errorf("failed to stat oldname: %v, err: %v", oldname, err) } linkdir := filepath.Dir(newname) err = MakeDirAll(linkdir) if err != nil { return fmt.Errorf("failed to make dir: %v, err: %v", linkdir, err) } // check link file is valid targetname, err := os.Readlink(newname) if err == nil { if targetname == oldname { return nil } } //link file is invalid os.Remove(newname) /* _, err = os.Stat(newname) if err != nil { if os.IsNotExist(err) { os.Remove(newname) } } */ err = os.Symlink(oldname, newname) if err != nil { return fmt.Errorf("failed to symlink err: %v", err) } _, err = os.Lstat(newname) if err != nil { return fmt.Errorf("failed to stat newname: %v, err: %v", newname, err) } return err } // include subdir, file and hidden file func ReadDirNames(path string, filterHiddenFile bool) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() names, err := file.Readdirnames(-1) if err != nil { return nil, err } if !filterHiddenFile { return names, nil } noHiddenFiles := []string{} for _, name := range names { if strings.HasPrefix(filepath.Base(name), ".") { continue } noHiddenFiles = append(noHiddenFiles, name) } return noHiddenFiles, nil } // only inlcude subdir // filterHiddenFile is true, then filter hidden files from result func ReadDirSubDirNames(path string, filterHiddenFile bool) ([]string, error) { names, err := ReadDirNames(path, filterHiddenFile) if err != nil { return nil, err } dirs := []string{} for _, name := range names { filePath := filepath.Join(path, name) ok, _ := IsDir(filePath) if ok { dirs = append(dirs, name) } } return dirs, nil } func ReadDirFileNames(path string, filterHiddenFile bool) ([]string, error) { names, err := ReadDirNames(path, filterHiddenFile) if err != nil { return nil, err } dirs := []string{} for _, name := range names { filePath := filepath.Join(path, name) ok, err := IsDir(filePath) if err == nil && !ok { dirs = append(dirs, name) } } return dirs, nil } ================================================ FILE: go/os/file_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os_test import ( "fmt" "io" "io/ioutil" "os" "path/filepath" "testing" io_ "github.com/kaydxh/golang/go/io" os_ "github.com/kaydxh/golang/go/os" "github.com/stretchr/testify/assert" ) func TestOpenAll(t *testing.T) { dir, err := ioutil.TempDir("", "dir") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(dir) f, err := os_.OpenAll(dir, os.O_CREATE, 0755) if err != nil { t.Errorf("expect nil, got %v", err) } _ = f fmt.Println(dir) for i := 0; i < 10; i++ { dirName := filepath.Join(dir, fmt.Sprintf("dir-%d", i)) f, err = os_.OpenAll(dirName, os.O_CREATE|os.O_RDWR, 0755) if err != nil { t.Errorf("expect nil, got %v", err) } defer f.Close() n, err := io.WriteString(f, "hello world") if err != nil { t.Errorf("expect nil, got %v", err) } assert.Equal(t, len("hello world"), n) fmt.Println(dirName) } } func TestSameFile(t *testing.T) { total := 2 fileNames := make([]string, total) dir, err := ioutil.TempDir("", "dir") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(dir) for i := 0; i < total; i++ { fileNames[i] = filepath.Join(dir, fmt.Sprintf("dir-%d", i)) buf := []byte("hello world") err = ioutil.WriteFile(fileNames[i], buf, 0777) if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println(fileNames[i]) } ok := os_.SameFile(fileNames[0], fileNames[0]) assert.Truef(t, ok, "fileName %s is the same of %s", fileNames[0], fileNames[0]) ok = os_.SameFile(fileNames[0], fileNames[1]) assert.Falsef(t, ok, "fileName %s is not the same of %s", fileNames[0], fileNames[1]) } func TestSymLink(t *testing.T) { dir, err := ioutil.TempDir("", "dir") if err != nil { t.Errorf("expect nil, got %v", err) } defer os.RemoveAll(dir) oldname := filepath.Join(dir, "oldname") buf := []byte("hello world") err = ioutil.WriteFile(oldname, buf, 0777) if err != nil { t.Errorf("expect nil, got %v", err) } newname := "test.link" err = os_.SymLink(oldname, newname) if err != nil { t.Fatalf("expect nil, got %v", err) } data, err := io_.ReadFile(newname) if err != nil { t.Errorf("expect nil, got %v", err) } assert.Equal(t, buf, data) } func TestPath(t *testing.T) { filename := "./workspace/studyspace/.././11.jpg" ///Users/kayxhding/workspace/studyspace/git-kayxhding/github.com/kaydxh/golang/go/os/workspace/11.jpg fmt.Println(filepath.Abs(filename)) //workspace/11.jpg fmt.Println(filepath.Clean(filename)) //../11.jpg fmt.Println(filepath.Rel("./workspace/22", filename)) } func TestReadDirNames(t *testing.T) { dir := "/usr/local" allFiles, err := os_.ReadDirNames(dir, true) if err != nil { t.Errorf("expect nil, got %v", err) } t.Logf("got sub dirs: %v", allFiles) } func TestReadSubDirs(t *testing.T) { dir := "/usr/local" subDirs, err := os_.ReadDirSubDirNames(dir, true) if err != nil { t.Errorf("expect nil, got %v", err) } t.Logf("got sub dirs: %v", subDirs) } func TestReadDirFileNames(t *testing.T) { dir := "/usr/local" fileNames, err := os_.ReadDirFileNames(dir, true) if err != nil { t.Errorf("expect nil, got %v", err) } t.Logf("got filenames: %v", fileNames) } func TestMakeTempDirAll(t *testing.T) { // /var/folders/by/jt3bf2n52fv6v7lrbndtdmjr0000gn/T/example690523200.12 dir, err := os_.MakeTempDirAll("", "example*.12") if err != nil { t.Errorf("expect nil, got %v", err) } t.Logf("got dir: %v", dir) } ================================================ FILE: go/os/getwd.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os import "os" func Getwd() (string, error) { return os.Getwd() } ================================================ FILE: go/os/getwd_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os_test import ( "fmt" "testing" os_ "github.com/kaydxh/golang/go/os" ) func TestGetwd(t *testing.T) { path, err := os_.Getwd() if err != nil { t.Errorf("expect nil, got %v", err) } fmt.Println(path) } ================================================ FILE: go/os/proc.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os import ( "fmt" "math/rand" "os" "strconv" "strings" "time" exec_ "github.com/kaydxh/golang/go/os/exec" ) func GetPidsByName( timeout time.Duration, name string) ([]int, string, error) { cmd := fmt.Sprintf( `ps ux | grep '%s'| grep -v grep | awk '{print $2}'`, name, ) result, msg, err := exec_.Exec(timeout, cmd) if err != nil { return nil, msg, err } pids := strings.TrimSpace(string(result)) sPids := strings.Split(pids, "\n") var nPids []int for _, pid := range sPids { nPid, err := strconv.Atoi(pid) if err != nil { return nil, msg, err } nPids = append(nPids, nPid) } return nPids, msg, nil } // 获取进程唯一标识符 func GetProcIdWithRand() string { s, _ := os.Hostname() return fmt.Sprintf("%s:pid:%v:%v", s, os.Getpid(), rand.Int()) } func GetProcId() string { s, _ := os.Hostname() return fmt.Sprintf("%s:pid:%v", s, os.Getpid()) } ================================================ FILE: go/os/proc_darwin.go ================================================ /* *Copyright (c) 2024, kaydxh * *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 os import "golang.org/x/sys/unix" func ExistPid(pid int) bool { // OS X & BSD systems don't have a proc filesystem. // Use kill -0 pid to judge if the process exists. err := unix.Kill(pid, 0) return err == nil } ================================================ FILE: go/os/proc_linux.go ================================================ /* *Copyright (c) 2024, kaydxh * *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 os import ( "os" "path/filepath" "strconv" ) func ExistPid(pid int) bool { _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid))) return err == nil // err is nil if file exists } ================================================ FILE: go/os/proc_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os_test import ( "testing" "time" os_ "github.com/kaydxh/golang/go/os" ) func TestGetPidsByName(t *testing.T) { timeout := 3000 pids, msg, err := os_.GetPidsByName(time.Duration(timeout), "kay") if err != nil { t.Errorf("expect nil, got %v, msg: %v", err, msg) } t.Logf("pids: %v", pids) } func TestExistPid(t *testing.T) { pid := 35458 exist := os_.ExistPid(pid) t.Logf("pid: %v %v", pid, exist) } ================================================ FILE: go/os/remove_file.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os import ( "os" errors_ "github.com/kaydxh/golang/go/errors" filepath_ "github.com/kaydxh/golang/go/path/filepath" ) func RemoveBatch(filenames []string) error { var errs []error for _, path := range filenames { err := os.Remove(path) if err != nil { errs = append(errs, err) } } return errors_.NewAggregate(errs) } func RemoveWithGlob(pattern string) error { matches, err := filepath_.Glob(pattern) if err != nil { return err } return RemoveBatch(matches) } ================================================ FILE: go/os/signal_posix.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os import ( "os" "syscall" ) //CTRL + C for SIGINT //docker stop for SIGTERM var ShutdownSignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM} ================================================ FILE: go/os/term/term.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 term import ( "fmt" "io" "github.com/moby/term" ) // TerminalSize returns the current width and height of the user's terminal. If it isn't a terminal, // nil is returned. On error, zero values are returned for width and height. // Usually w must be the stdout of the process. Stderr won't work. func TerminalSize(w io.Writer) (int, int, error) { outFd, isTerminal := term.GetFdInfo(w) if !isTerminal { return 0, 0, fmt.Errorf("given writer is no terminal") } winsize, err := term.GetWinsize(outFd) if err != nil { return 0, 0, err } return int(winsize.Width), int(winsize.Height), nil } ================================================ FILE: go/os/value.go ================================================ package os func GetValueOrFallback[T comparable](v, defaultValue T) T { var zeroE T if v != zeroE { return v } return defaultValue } ================================================ FILE: go/os/value_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 os_test import ( "fmt" "testing" os_ "github.com/kaydxh/golang/go/os" ) func TestGetOrFallback(t *testing.T) { testCases := []struct { value string defaultValue string expected string }{ { value: "value", defaultValue: "defaultValue", expected: "value", }, { value: "", defaultValue: "defaultValue", expected: "defaultValue", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { v := os_.GetValueOrFallback(testCase.value, testCase.defaultValue) if v != testCase.expected { t.Fatalf("failed to get or fall back, got : %s", v) } t.Logf("got value: %v", v) }) } } ================================================ FILE: go/path/filepath/match.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filepath import ( "os" "path/filepath" ) func Glob(pattern string) (matches []string, err error) { matches, err = filepath.Glob(pattern) if err != nil { return nil, err } matchFilters := make([]string, 0, len(matches)) for _, path := range matches { _, err := os.Stat(path) if err != nil { continue } _, err = os.Lstat(path) if err != nil { continue } matchFilters = append(matchFilters, path) } return matchFilters, nil } ================================================ FILE: go/path/filepath/path.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filepath import ( "path" "path/filepath" ) func GetParentRelPath(filePath string) string { fileName := path.Base(filePath) parentDir := GetParentRelDir(filePath) return filepath.Join(parentDir, fileName) } func GetParentRelDir(filePath string) string { dir := path.Dir(filePath) return path.Base(dir) } func LastChar(str string) uint8 { if str == "" { // char '0' means dec 48, 0 means null return 0 } return str[len(str)-1] } // join paths, keep relativePath suffix func JoinPaths(rootPath, relativePath string) (string, error) { absolutePath, err := filepath.Abs(rootPath) if err != nil { return "", err } if relativePath == "" { return absolutePath, nil } finalPath := path.Join(absolutePath, relativePath) if LastChar(relativePath) == '/' && LastChar(finalPath) != '/' { return finalPath + "/", nil } return finalPath, nil } // CanonicalizePath turns path into an absolute path without symlinks. func CanonicalizePath(path string) (string, error) { path, err := filepath.Abs(path) if err != nil { return "", err } activepath, err := filepath.EvalSymlinks(path) if err == nil { return activepath, nil } /* // Get a better error if we have an invalid path if pathErr, ok := err.(*os.PathError); ok { err = errors.Wrap(pathErr.Err, pathErr.Path) } */ return path, nil } ================================================ FILE: go/path/filepath/path_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filepath_test import ( "fmt" "path/filepath" "testing" filepath_ "github.com/kaydxh/golang/go/path/filepath" "github.com/stretchr/testify/assert" ) func TestGetParentRelPath(t *testing.T) { testCases := []struct { filePath string expected string }{ { filePath: "/data/home/deploy/bin/run.exe", expected: "bin/run.exe", }, { filePath: "/run.exe", expected: "/run.exe", }, } for _, testCase := range testCases { t.Run(testCase.filePath, func(t *testing.T) { rel := filepath_.GetParentRelPath(testCase.filePath) assert.Equal(t, testCase.expected, rel) t.Logf("rel: %v", rel) }) } } func TestAbsPath(t *testing.T) { testCases := []struct { filePath string expected string }{ { filePath: "", expected: "", }, { filePath: ".", expected: "", }, } for _, testCase := range testCases { t.Run(testCase.filePath, func(t *testing.T) { abs, err := filepath.Abs(testCase.filePath) if err != nil { t.Fatalf("abs err: %v", err) } t.Logf("abs: %v", abs) }) } } func TestJoinPaths(t *testing.T) { testCases := []struct { absolutePath string relativePath string expected string }{ { absolutePath: "/data", relativePath: "./relative", expected: "", }, { absolutePath: "./data", relativePath: "./relative", expected: "", }, { absolutePath: "./data", relativePath: "./relative/", expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("test-case-%d", i), func(t *testing.T) { fullPath, err := filepath_.JoinPaths(testCase.absolutePath, testCase.relativePath) if err != nil { t.Fatalf("joinPaths err: %v", err) } t.Logf("fullPath : %v", fullPath) }) } } ================================================ FILE: go/reflect/array.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 reflect import ( "reflect" ) func ArrayAllTagsVaules(req interface{}, key string) []map[string]interface{} { sliceValues := reflect.ValueOf(req) var valuesMap []map[string]interface{} for i := 0; i < sliceValues.Len(); i++ { structValue := sliceValues.Index(i) structType := structValue.Type() tagValues := make(map[string]interface{}) if structType.Kind() == reflect.Ptr { structType = structType.Elem() structValue = structValue.Elem() } if !structValue.CanInterface() { continue } tagValues = AllTagsValues(structValue.Interface(), key) /* // get tags for struct if structType.Kind() != reflect.Struct { return nil } for j := 0; j < structType.NumField(); j++ { field := structType.Field(j) value := structValue.Field(j) if !value.CanInterface() { continue } tag := field.Tag.Get(key) if tag != "" { tagValues[tag] = value.Interface() } } */ valuesMap = append(valuesMap, tagValues) } return valuesMap } ================================================ FILE: go/reflect/array_test.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 reflect_test import ( "testing" reflect_ "github.com/kaydxh/golang/go/reflect" ) func TestPointerStructArrayAllTagsValues(t *testing.T) { type HttpRequest struct { RequestId string `db:"request_id"` Username string `db:"username"` } req := []*HttpRequest{ &HttpRequest{ RequestId: "123", Username: "123-username", }, &HttpRequest{ RequestId: "456", Username: "456-username", }, } tagsValues := reflect_.ArrayAllTagsVaules(req, "db") t.Logf("tagsValues: %v", tagsValues) //assert.Equal(t, []string{"request_id"}, fields) } func TestStructArrayAllTagsValues(t *testing.T) { type HttpRequest struct { RequestId string `db:"request_id"` Username string `db:"username"` } req := []HttpRequest{ HttpRequest{ RequestId: "123", Username: "123-username", }, HttpRequest{ RequestId: "456", Username: "456-username", }, } tagsValues := reflect_.ArrayAllTagsVaules(req, "db") t.Logf("tagsValues: %v", tagsValues) //assert.Equal(t, []string{"request_id"}, fields) } ================================================ FILE: go/reflect/error.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 reflect import "fmt" // ErrUnsupportedType ... type ErrUnsupportedType struct { valueType string } // NewErrUnsupportedType returns new ErrUnsupportedType func NewErrUnsupportedType(valueType string) ErrUnsupportedType { return ErrUnsupportedType{valueType} } // Error method so we implement the error interface func (e ErrUnsupportedType) Error() string { return fmt.Sprintf("%v is not one of supported types", e.valueType) } ================================================ FILE: go/reflect/id.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 reflect var ( FieldNameRequestId = "RequestId" FieldNameSessionId = "SessionId" ) type IdRetriever interface { GetId() string } func RetrieveId(req interface{}, key string) string { if req == nil { return "" } // if defined GetRequestId()string method, use it get requestId if req, ok := req.(IdRetriever); ok { if req != nil { return req.GetId() } } return RetrieveStructField(req, key) } func TrySetId(req interface{}, key, id string) { TrySetStructFiled(req, key, id) } ================================================ FILE: go/reflect/struct.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 reflect import ( "reflect" ) //req must be pointer to struct // IsNil reports whether its argument v is nil. The argument must be // a chan, func, interface, map, pointer, or slice value; if it is // not, IsNil panics. Note that IsNil is not always equivalent to a // regular comparison with nil in Go. For example, if v was created // by calling ValueOf with an uninitialized interface variable i, // i==nil will be true but v.IsNil will panic as v will be the zero // Value. func indirectStruct(req interface{}) (reflect.Value, bool) { if req == nil { return reflect.Value{}, false } v := reflect.ValueOf(req) /* if v.IsNil() { return reflect.Value{}, false } */ return reflect.Indirect(v), true } func RetrieveStructField(req interface{}, name string) string { v, ok := indirectStruct(req) if !ok { return "" } if !v.IsValid() { return "" } //nested field: reflect.Indirect(v).FieldByName("layout1").Index(0).FieldByName("layout2") f := v.FieldByName(name) if f.IsValid() && f.Kind() == reflect.String { return f.String() } return "" } func TrySetStructFiled(req interface{}, name, value string) { v, ok := indirectStruct(req) if !ok { return } if !v.IsValid() { return } f := v.FieldByName(name) if f.IsValid() && f.Kind() == reflect.String { f.SetString(value) } } func AllFieldTags(req interface{}, key string) []string { return fieldTags(req, key, false) } // req must be struct(Not pointer to struct), or return nil(tt.Field() will panic) // key for tag , db or json, if key is empty, use field name instead func NonzeroFieldTags(req interface{}, key string) []string { return fieldTags(req, key, true) } // req must be struct(Not pointer to struct), or return nil(tt.Field() will panic) // key for tag , db or json, if key is empty, use field name instead //nonzere true, noly return field tags for values that nonzero func fieldTags(req interface{}, key string, nonzero bool) []string { var tags []string tagsValues := fieldTagsValues(req, key, nonzero) for tag := range tagsValues { tags = append(tags, tag) } return tags } // only get export Fields func AllTagsValues(req interface{}, key string) map[string]interface{} { return fieldTagsValues(req, key, false) } // req must be struct(Not pointer to struct), or return nil(tt.Field() will panic) // key for tag , db or json ..., if key is empty or tag is empty, ignore it // nonzere true, noly return field tags for values that nonzero func fieldTagsValues(req interface{}, key string, nonzero bool) map[string]interface{} { if req == nil { return nil } v, ok := indirectStruct(req) if !ok { return nil } if !v.IsValid() { return nil } tt := reflect.TypeOf(req) if tt.Kind() == reflect.Ptr { tt = tt.Elem() } if tt.Kind() != reflect.Struct { return nil } tagsValues := make(map[string]interface{}) for i := 0; i < tt.NumField(); i++ { field := tt.Field(i) property := string(field.Name) f := v.FieldByName(property) if !f.CanInterface() { continue } if nonzero { if IsZeroValue(f) { continue } } if key == "" { continue } tag := field.Tag.Get(key) if len(tag) > 0 { // field.Type.Name() -> "string", "int64" ... tagsValues[tag] = f.Interface() } } return tagsValues } ================================================ FILE: go/reflect/struct_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 reflect_test import ( "testing" "github.com/google/uuid" reflect_ "github.com/kaydxh/golang/go/reflect" "github.com/stretchr/testify/assert" ) func TestRetrieveStructField(t *testing.T) { type HttpRequest struct { RequestId string Username string } id := uuid.NewString() req := &HttpRequest{ RequestId: id, } requestId := reflect_.RetrieveStructField(req, "RequestId") t.Logf("requestId: %v", requestId) assert.Equal(t, id, requestId) } func TestTrySetStructField(t *testing.T) { type HttpRequest struct { RequestId string Username string } id := uuid.NewString() req := &HttpRequest{ // RequestId: id, } reflect_.TrySetStructFiled(req, "RequestId", id) t.Logf("requestId: %v", req.RequestId) assert.Equal(t, id, req.RequestId) } func TestNonzeroFieldTags(t *testing.T) { type HttpRequest struct { RequestId string `db:"request_id"` Username string `db:"username"` } id := uuid.NewString() req := &HttpRequest{ RequestId: id, // Username: "username 1", } fields := reflect_.NonzeroFieldTags(req, "db") t.Logf("fields: %v", fields) assert.Equal(t, []string{"request_id"}, fields) } func TestAllFieldTags(t *testing.T) { type HttpRequest struct { RequestId string `db:"request_id"` Username string `db:"username"` } id := uuid.NewString() req := HttpRequest{ RequestId: id, // Username: "username 1", } fields := reflect_.AllFieldTags(req, "db") t.Logf("fields: %v", fields) //assert.Equal(t, []string{"request_id"}, fields) } func TestAllTagsValues(t *testing.T) { type HttpRequest struct { RequestId string `db:"request_id"` Username string `db:"username"` } id := uuid.NewString() req := &HttpRequest{ RequestId: id, Username: "admin", } tagsValues := reflect_.AllTagsValues(req, "db") t.Logf("tagsValues: %v", tagsValues) //assert.Equal(t, []string{"request_id"}, fields) } ================================================ FILE: go/reflect/truncate.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 reflect import ( "bytes" "fmt" "reflect" ) const ( // DefaultTruncateThreshold 默认截断阈值,超过此长度才截断 DefaultTruncateThreshold = 1024 // DefaultTruncatePrefix 默认保留的前缀字节数 DefaultTruncatePrefix = 10 // MaxTruncateDepth 最大递归深度,防止循环引用(如 google.protobuf.Struct)导致堆栈溢出 MaxTruncateDepth = 32 ) func TruncateBytes(v interface{}) interface{} { return TruncateBytesWithThreshold(v, DefaultTruncateThreshold, DefaultTruncatePrefix) } // TruncateBytesWithThreshold 截断 []byte 类型字段,超过 threshold 长度时保留前 prefix 字节并附带总长度 func TruncateBytesWithThreshold(v interface{}, threshold, prefix int) interface{} { return Truncate(v, func(v interface{}) bool { _, ok := v.([]byte) return ok }, threshold, prefix) } // TruncateBytesAndStrings 同时截断 []byte 和 string 类型字段 func TruncateBytesAndStrings(v interface{}) interface{} { return TruncateBytesAndStringsWithThreshold(v, DefaultTruncateThreshold, DefaultTruncatePrefix) } // TruncateBytesAndStringsWithThreshold 截断 []byte 和 string 类型字段,超过 threshold 长度时保留前 prefix 字节并附带总长度 func TruncateBytesAndStringsWithThreshold(v interface{}, threshold, prefix int) interface{} { return Truncate(v, func(v interface{}) bool { switch v.(type) { case []byte: return true case string: return true } return false }, threshold, prefix) } func Truncate(v interface{}, f func(v interface{}) bool, threshold, prefix int) interface{} { truncate(reflect.ValueOf(v), f, threshold, prefix, 0) return v } //https://stackoverflow.com/questions/6395076/using-reflect-how-do-you-set-the-value-of-a-struct-field // truncate []byte, [][]byte, string, map values, not support others, eg: [][][]byte // struct must use pointer of struct, or not rewrite it // depth 参数用于限制递归深度,防止循环引用(如 google.protobuf.Struct)导致堆栈溢出 func truncate(v reflect.Value, f func(v interface{}) bool, threshold, prefix int, depth int) { if !v.IsValid() { return } if v.Type() == nil { return } // 递归深度限制,防止循环引用(如 google.protobuf.Struct -> Value -> Struct)导致堆栈溢出 if depth > MaxTruncateDepth { return } if v.CanInterface() { vv := v.Interface() if f(vv) { truncateToLen(v, threshold, prefix) } } switch v.Kind() { case reflect.Struct: for i := 0; i < v.NumField(); i++ { truncate(v.Field(i), f, threshold, prefix, depth+1) } case reflect.Array, reflect.Slice: for i := 0; i < v.Len(); i++ { truncate(v.Index(i), f, threshold, prefix, depth+1) } case reflect.Ptr: if !v.IsNil() { truncate(reflect.Indirect(v), f, threshold, prefix, depth+1) } case reflect.Map: iter := v.MapRange() for iter.Next() { mapVal := iter.Value() // map 的 value 不能直接修改,需要通过 Elem 解引用指针后修改 if mapVal.Kind() == reflect.Ptr && !mapVal.IsNil() { truncate(mapVal.Elem(), f, threshold, prefix, depth+1) } else if mapVal.Kind() == reflect.Interface && !mapVal.IsNil() { truncate(mapVal.Elem(), f, threshold, prefix, depth+1) } } case reflect.Interface: if !v.IsNil() { truncate(v.Elem(), f, threshold, prefix, depth+1) } default: } return } func truncateToLen(oldValue reflect.Value, threshold, prefix int) { if !oldValue.IsValid() { return } if !oldValue.CanInterface() { return } vv := oldValue.Interface() switch vv := vv.(type) { case []byte: if len(vv) > threshold { writeBytesLenToReflectValue(oldValue, vv, prefix) } case string: if len(vv) > threshold { writeStringLenToReflectValue(oldValue, vv, prefix) } } return } // writeBytesLenToReflectValue 将 []byte 截断为前 prefix 字节 + 总长度信息 func writeBytesLenToReflectValue(v reflect.Value, data []byte, prefix int) interface{} { // if v can not set, return truncate result if !v.CanAddr() { return fmt.Sprintf("%s...(bytes len: %d)", string(data[:min(prefix, len(data))]), len(data)) } var buf bytes.Buffer if prefix > 0 && prefix < len(data) { buf.Write(data[:prefix]) buf.WriteString(fmt.Sprintf("...(bytes len: %d)", len(data))) } else { buf.WriteString(fmt.Sprintf("bytes len: %d", len(data))) } v.SetBytes(buf.Bytes()) return v } // writeStringLenToReflectValue 将 string 截断为前 prefix 字节 + 总长度信息 func writeStringLenToReflectValue(v reflect.Value, data string, prefix int) { if !v.CanSet() { return } if prefix > 0 && prefix < len(data) { v.SetString(fmt.Sprintf("%s...(string len: %d)", data[:prefix], len(data))) } else { v.SetString(fmt.Sprintf("string len: %d", len(data))) } } func min(a, b int) int { if a < b { return a } return b } ================================================ FILE: go/reflect/truncate_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 reflect_test import ( "fmt" "strings" "testing" // "github.com/google/uuid" "github.com/google/uuid" reflect_ "github.com/kaydxh/golang/go/reflect" ) func TestTruncateBytes(t *testing.T) { tmp := []byte("12345678") tmp2 := [][]byte{[]byte("12345678"), []byte("12345678")} _ = tmp testCases := []struct { req interface{} }{ { req: &struct { RequestId string Image []byte Item struct { a int Image []byte } }{ RequestId: uuid.New().String(), Image: []byte("12345678"), Item: struct { a int Image []byte }{ a: 1, Image: []byte("12345678"), }, }, }, { req: []byte("12345678"), }, { req: &tmp, }, { req: [][]byte{[]byte("12345678"), []byte("12345678")}, }, { req: &tmp2, }, { req: &struct { Images [][]byte }{ Images: [][]byte{ []byte("12345678"), []byte("12345678"), }, }, }, { req: &struct { Images [][][]byte }{ Images: [][][]byte{ [][]byte{[]byte("12345678")}, [][]byte{[]byte("12345678")}, }, }, }, { req: &struct { RequstId string FrameImage []byte Jobs []struct { JobType int JobOutput struct { OccupyData struct { GroupCode string FrameImage []byte } } } }{ RequstId: "RRRRRRID", FrameImage: []byte("frame data"), Jobs: []struct { JobType int JobOutput struct { OccupyData struct { GroupCode string FrameImage []byte } } }{ { JobType: 1, JobOutput: struct { OccupyData struct { GroupCode string FrameImage []byte } }{ OccupyData: struct { GroupCode string FrameImage []byte }{ GroupCode: "group code", FrameImage: []byte("frame data"), }, }, }, }, }, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%v", i), func(t *testing.T) { t.Logf("req: %+v\n, ", testCase.req) truncateReq := reflect_.TruncateBytes(testCase.req) //t.Logf("req: %+v\n, truncateReq: %+v", testCase.req, truncateReq) t.Logf("truncateReq: %+v", truncateReq) }) } } func TestTruncateBytesWithMaxArraySize(t *testing.T) { testCases := []struct { req interface{} }{ { req: &struct { RequestId string Image []byte Item []struct { a int Image []byte } }{ RequestId: uuid.New().String(), Image: []byte("12345678"), Item: []struct { a int Image []byte }{ { a: 1, Image: []byte("12345678"), }, { a: 2, Image: []byte("12345678"), }, { a: 3, Image: []byte("12345678"), }, }, }, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%v", i), func(t *testing.T) { t.Logf("req: %+v\n", testCase.req) // truncateReq := reflect_.TruncateBytesWithMaxArraySize(testCase.req, 1) // t.Logf("truncateReq: %+v", truncateReq) }) } } func TestTruncateBytesWithThreshold(t *testing.T) { // 生成超过 1024 字节的数据 longBytes := make([]byte, 2048) for i := range longBytes { longBytes[i] = byte('A' + (i % 26)) } shortBytes := []byte("short data") testCases := []struct { name string req interface{} expectTrunc bool // 是否期望被截断 }{ { name: "bytes超过阈值应被截断", req: &struct { RequestId string Image []byte }{ RequestId: "test-id", Image: longBytes, }, expectTrunc: true, }, { name: "bytes未超过阈值不应被截断", req: &struct { RequestId string Image []byte }{ RequestId: "test-id", Image: shortBytes, }, expectTrunc: false, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { result := reflect_.TruncateBytes(tc.req) t.Logf("truncateReq: %+v", result) }) } } func TestTruncateBytesAndStrings(t *testing.T) { // 生成超过 1024 字节的数据 longString := strings.Repeat("ABCDEFGHIJ", 200) // 2000 字节 shortString := "short string" longBytes := make([]byte, 2048) for i := range longBytes { longBytes[i] = byte('0' + (i % 10)) } shortBytes := []byte("short bytes") testCases := []struct { name string req interface{} }{ { name: "string和bytes都超过阈值", req: &struct { RequestId string Data string Image []byte }{ RequestId: "test-id", Data: longString, Image: longBytes, }, }, { name: "string和bytes都未超过阈值", req: &struct { RequestId string Data string Image []byte }{ RequestId: "test-id", Data: shortString, Image: shortBytes, }, }, { name: "嵌套结构体中的长string和bytes", req: &struct { RequestId string Item struct { Name string Image []byte } }{ RequestId: "test-id", Item: struct { Name string Image []byte }{ Name: longString, Image: longBytes, }, }, }, { name: "自定义阈值测试", req: &struct { Data string }{ Data: "hello world, this is a test string", }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { t.Logf("before: %+v", tc.req) result := reflect_.TruncateBytesAndStrings(tc.req) t.Logf("after: %+v", result) }) } // 单独测试自定义阈值 t.Run("自定义阈值-threshold=10-prefix=5", func(t *testing.T) { req := &struct { Data string Image []byte }{ Data: "hello world, this is a long string", Image: []byte("hello world, this is long bytes"), } t.Logf("before: %+v", req) result := reflect_.TruncateBytesAndStringsWithThreshold(req, 10, 5) t.Logf("after: %+v", result) }) } // TestTruncateWithMap 测试包含 map 类型的结构体截断(模拟 google.protobuf.Struct 场景) func TestTruncateWithMap(t *testing.T) { longBytes := make([]byte, 2048) for i := range longBytes { longBytes[i] = byte('X') } testCases := []struct { name string req interface{} }{ { name: "包含map的结构体", req: &struct { Fields map[string]*struct { Data string Image []byte } }{ Fields: map[string]*struct { Data string Image []byte }{ "key1": { Data: strings.Repeat("A", 2000), Image: longBytes, }, "key2": { Data: "short", Image: []byte("short"), }, }, }, }, { name: "包含map[string]interface{}的结构体", req: &struct { Meta map[string]interface{} }{ Meta: map[string]interface{}{ "name": "test", }, }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { t.Logf("before: %+v", tc.req) result := reflect_.TruncateBytesAndStrings(tc.req) t.Logf("after: %+v", result) }) } } // TestTruncateWithCircularLikeStruct 测试模拟循环引用结构(类似 google.protobuf.Struct)不会堆栈溢出 func TestTruncateWithCircularLikeStruct(t *testing.T) { // 模拟 google.protobuf.Struct 的循环引用结构 type Value struct { StringValue string BytesValue []byte StructValue *struct { Fields map[string]*Value } } type Struct struct { Fields map[string]*Value } req := &Struct{ Fields: map[string]*Value{ "image_data": { BytesValue: make([]byte, 2048), }, "long_text": { StringValue: strings.Repeat("Z", 2000), }, "nested": { StructValue: &struct { Fields map[string]*Value }{ Fields: map[string]*Value{ "inner_data": { BytesValue: make([]byte, 1500), }, }, }, }, }, } // 这个测试的关键是:不会因为类似循环引用的结构导致堆栈溢出 t.Logf("before: %+v", req) result := reflect_.TruncateBytesAndStrings(req) t.Logf("after: %+v", result) } ================================================ FILE: go/reflect/value.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 reflect import ( "context" "encoding/json" "fmt" "math" "reflect" "strings" ) var ( typesMap = map[string]reflect.Type{ // base types "bool": reflect.TypeOf(true), "int": reflect.TypeOf(int(1)), "int8": reflect.TypeOf(int8(1)), "int16": reflect.TypeOf(int16(1)), "int32": reflect.TypeOf(int32(1)), "int64": reflect.TypeOf(int64(1)), "uint": reflect.TypeOf(uint(1)), "uint8": reflect.TypeOf(uint8(1)), "uint16": reflect.TypeOf(uint16(1)), "uint32": reflect.TypeOf(uint32(1)), "uint64": reflect.TypeOf(uint64(1)), "float32": reflect.TypeOf(float32(0.5)), "float64": reflect.TypeOf(float64(0.5)), "string": reflect.TypeOf(string("")), // slices "[]bool": reflect.TypeOf(make([]bool, 0)), "[]int": reflect.TypeOf(make([]int, 0)), "[]int8": reflect.TypeOf(make([]int8, 0)), "[]int16": reflect.TypeOf(make([]int16, 0)), "[]int32": reflect.TypeOf(make([]int32, 0)), "[]int64": reflect.TypeOf(make([]int64, 0)), "[]uint": reflect.TypeOf(make([]uint, 0)), "[]uint8": reflect.TypeOf(make([]uint8, 0)), "[]uint16": reflect.TypeOf(make([]uint16, 0)), "[]uint32": reflect.TypeOf(make([]uint32, 0)), "[]uint64": reflect.TypeOf(make([]uint64, 0)), "[]float32": reflect.TypeOf(make([]float32, 0)), "[]float64": reflect.TypeOf(make([]float64, 0)), "[]byte": reflect.TypeOf(make([]byte, 0)), "[]string": reflect.TypeOf([]string{""}), } ctxType = reflect.TypeOf((*context.Context)(nil)).Elem() typeConversionError = func(argValue interface{}, argTypeStr string) error { return fmt.Errorf("%v is not %v", argValue, argTypeStr) } ) // cmd/compile/internal/gc/dump.go func IsZeroValue(v reflect.Value) bool { if !v.IsValid() { return true } switch v.Kind() { case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return math.Float64bits(v.Float()) == 0 case reflect.Complex64, reflect.Complex128: c := v.Complex() return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0 case reflect.String: return v.String() == "" case reflect.Array: for i := 0; i < v.Len(); i++ { if !v.Index(i).IsZero() { return false } } return true case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: return v.IsNil() case reflect.Struct: for i := 0; i < v.NumField(); i++ { if !v.Field(i).IsZero() { return false } } return true default: } return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) } // ReflectValue converts interface{} to reflect.Value based on string type func ReflectValue(valueType string, value interface{}) (reflect.Value, error) { /* if strings.HasPrefix(valueType, "[]") { return reflectValues(valueType, value) } */ return reflectValue(valueType, value) } // reflectValue converts interface{} to reflect.Value based on string type // representing a base type (not a slice) func reflectValue(valueType string, value interface{}) (reflect.Value, error) { theType, ok := typesMap[valueType] if !ok { return reflect.Value{}, NewErrUnsupportedType(valueType) } theValue := reflect.New(theType) // Booleans if theType.String() == "bool" { boolValue, err := getBoolValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetBool(boolValue) return theValue.Elem(), nil } // Integers if strings.HasPrefix(theType.String(), "int") { intValue, err := getIntValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetInt(intValue) return theValue.Elem(), err } // Unsigned integers if strings.HasPrefix(theType.String(), "uint") { uintValue, err := getUintValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetUint(uintValue) return theValue.Elem(), err } // Floating point numbers if strings.HasPrefix(theType.String(), "float") { floatValue, err := getFloatValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetFloat(floatValue) return theValue.Elem(), err } // Strings if theType.String() == "string" { stringValue, err := getStringValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetString(stringValue) return theValue.Elem(), nil } return reflect.Value{}, NewErrUnsupportedType(valueType) } func getBoolValue(theType string, value interface{}) (bool, error) { b, ok := value.(bool) if !ok { return false, typeConversionError(value, typesMap[theType].String()) } return b, nil } func getIntValue(theType string, value interface{}) (int64, error) { // We use https://golang.org/pkg/encoding/json/#Decoder.UseNumber when unmarshaling signatures. // This is because JSON only supports 64-bit floating point numbers and we could lose precision // when converting from float64 to signed integer if strings.HasPrefix(fmt.Sprintf("%T", value), "json.Number") { n, ok := value.(json.Number) if !ok { return 0, typeConversionError(value, typesMap[theType].String()) } return n.Int64() } var n int64 switch value := value.(type) { case int: n = int64(value) case int64: n = value case int32: n = int64(value) case int16: n = int64(value) case int8: n = int64(value) default: fmt.Printf("value: %v\n", value) return 0, typeConversionError(value, typesMap[theType].String()) } return n, nil } func getUintValue(theType string, value interface{}) (uint64, error) { // We use https://golang.org/pkg/encoding/json/#Decoder.UseNumber when unmarshaling signatures. // This is because JSON only supports 64-bit floating point numbers and we could lose precision // when converting from float64 to unsigned integer if strings.HasPrefix(fmt.Sprintf("%T", value), "json.Number") { n, ok := value.(json.Number) if !ok { fmt.Printf("00000\n") return 0, typeConversionError(value, typesMap[theType].String()) } intVal, err := n.Int64() if err != nil { return 0, err } return uint64(intVal), nil } var n uint64 switch value := value.(type) { case uint: n = uint64(value) case uint64: n = value case uint32: n = uint64(value) case uint16: n = uint64(value) case uint8: n = uint64(value) default: fmt.Printf("value: %v\n", value) return 0, typeConversionError(value, typesMap[theType].String()) } return n, nil } func getFloatValue(theType string, value interface{}) (float64, error) { // We use https://golang.org/pkg/encoding/json/#Decoder.UseNumber when unmarshaling signatures. // This is because JSON only supports 64-bit floating point numbers and we could lose precision if strings.HasPrefix(fmt.Sprintf("%T", value), "json.Number") { n, ok := value.(json.Number) if !ok { return 0, typeConversionError(value, typesMap[theType].String()) } return n.Float64() } f, ok := value.(float64) if !ok { return 0, typeConversionError(value, typesMap[theType].String()) } return f, nil } func getStringValue(theType string, value interface{}) (string, error) { s, ok := value.(string) if !ok { return "", typeConversionError(value, typesMap[theType].String()) } return s, nil } ================================================ FILE: go/reflect/value_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 reflect_test import ( "testing" reflect_ "github.com/kaydxh/golang/go/reflect" ) func TestReflectValue(t *testing.T) { testCases := []struct { valueType string value interface{} expected string }{ { valueType: "bool", value: true, expected: "", }, { valueType: "int", value: 123456789, expected: "", }, { valueType: "uint", value: uint(123456789), expected: "", }, { valueType: "float32", value: 0.123456789, expected: "", }, } for _, testCase := range testCases { t.Run(testCase.valueType, func(t *testing.T) { rvalue, err := reflect_.ReflectValue(testCase.valueType, testCase.value) if err != nil { t.Fatalf("failed to reflect value: %v, got : %s", testCase.value, err) } t.Logf("reflect value: %v", rvalue) }) } } ================================================ FILE: go/runtime/extern.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime import ( "fmt" "path" "runtime" "strings" ) // GetCaller returns the caller of the function that calls it. //The argument skip is the number of stack frames to skip before recording in pc, with 0 identifying the frame for Callers itself and 1 identifying the caller of Callers func GetCallerWithSkip(skip int) string { var pc [1]uintptr runtime.Callers(skip+1, pc[:]) f := runtime.FuncForPC(pc[0]) if f == nil { return fmt.Sprintf("Unable to find caller") } return f.Name() } func GetCaller() string { //4 skip, 1 GetCaller, 1 GetCallerWithSkip, 1 runtime.Callers, 1 caller of GetCaller return GetCallerWithSkip(3) } func GetShortCaller() string { fn := GetCallerWithSkip(3) return strings.TrimPrefix(path.Ext(fn), ".") } func GetCallStackTrace() string { const size = 64 << 10 stacktrace := make([]byte, size) stacktrace = stacktrace[:runtime.Stack(stacktrace, false)] return string(stacktrace) } ================================================ FILE: go/runtime/extern_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime_test import ( "testing" runtime_ "github.com/kaydxh/golang/go/runtime" ) func TestGetCaller(t *testing.T) { // fn shoud be testing.tRunner, caller of TestGetParentCaller fn := runtime_.GetCaller() t.Logf("fn: %v", fn) } ================================================ FILE: go/runtime/function.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime import ( "reflect" "runtime" ) func NameOfFunction(f interface{}) string { v := reflect.ValueOf(f) if v.Kind() == reflect.Func { return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() } return "???" } ================================================ FILE: go/runtime/function_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime_test import ( "fmt" "testing" runtime_ "github.com/kaydxh/golang/go/runtime" "github.com/stretchr/testify/assert" ) func testA(a int) int { return a } func TestNameOfFunction(t *testing.T) { testCases := []struct { f interface{} expected string }{ { f: func(a int) int { return a }, expected: "github.com/kaydxh/golang/go/runtime_test.TestNameOfFunction.func1", }, { f: func(a int) int { return a }, expected: "github.com/kaydxh/golang/go/runtime_test.TestNameOfFunction.func2", }, { f: testA, expected: "github.com/kaydxh/golang/go/runtime_test.testA", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("test-case-%d", i), func(t *testing.T) { funcName := runtime_.NameOfFunction(testCase.f) assert.Equal(t, testCase.expected, funcName) t.Logf("funcName: %v", funcName) }) } } ================================================ FILE: go/runtime/goroutine.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime import ( "bytes" "errors" "fmt" "runtime" "strconv" "sync" ) var goroutineSpace = []byte("goroutine ") //low performance func GoroutineID() uint64 { bp := littleBuf.Get().(*[]byte) defer littleBuf.Put(bp) b := *bp b = b[:runtime.Stack(b, false)] // Parse the 4707 out of "goroutine 4707 [" b = bytes.TrimPrefix(b, goroutineSpace) i := bytes.IndexByte(b, ' ') if i < 0 { panic(fmt.Sprintf("No space found in %q", b)) } b = b[:i] n, err := parseUintBytes(b, 10, 64) if err != nil { panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) } return n } var littleBuf = sync.Pool{ New: func() interface{} { buf := make([]byte, 64) return &buf }, } // parseUintBytes is like strconv.ParseUint, but using a []byte. func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) { var cutoff, maxVal uint64 if bitSize == 0 { bitSize = int(strconv.IntSize) } s0 := s switch { case len(s) < 1: err = strconv.ErrSyntax goto Error case 2 <= base && base <= 36: // valid base; nothing to do case base == 0: // Look for octal, hex prefix. switch { case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'): base = 16 s = s[2:] if len(s) < 1 { err = strconv.ErrSyntax goto Error } case s[0] == '0': base = 8 default: base = 10 } default: err = errors.New("invalid base " + strconv.Itoa(base)) goto Error } n = 0 cutoff = cutoff64(base) maxVal = 1<= base { n = 0 err = strconv.ErrSyntax goto Error } if n >= cutoff { // n*base overflows n = 1<<64 - 1 err = strconv.ErrRange goto Error } n *= uint64(base) n1 := n + uint64(v) if n1 < n || n1 > maxVal { // n+v overflows n = 1<<64 - 1 err = strconv.ErrRange goto Error } n = n1 } return n, nil Error: return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err} } // Return the first number n such that n*base >= 1<<64. func cutoff64(base int) uint64 { if base < 2 { return 0 } return (1<<64-1)/uint64(base) + 1 } ================================================ FILE: go/runtime/marshaler/jsonpb.marshaler.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 marshaler import ( "encoding/json" "fmt" structpb "github.com/golang/protobuf/ptypes/struct" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/protobuf/proto" ) type JSONPb struct { runtime.JSONPb opts struct { useProtoNames bool useEnumNumbers bool emitUnpopulated bool discardUnknown bool allowPartial bool indent string } } func NewDefaultJSONPb() *JSONPb { return NewJSONPb( // ummarshal for input // marshal for output // use json name // only for mashaler WithUseProtoNames(false), //false means use enum string for output WithUseEnumNumbers(false), WithEmitUnpopulated(true), WithIndent("\t"), // only for unmarshal WithDiscardUnknown(true), // for marshal , unmarshal WithAllowPartial(true), ) } func NewJSONPb(options ...JSONPbOption) *JSONPb { j := &JSONPb{} j.ApplyOptions(options...) if j.opts.useProtoNames { j.MarshalOptions.UseProtoNames = true } if j.opts.useEnumNumbers { j.MarshalOptions.UseEnumNumbers = true } if j.opts.emitUnpopulated { j.MarshalOptions.EmitUnpopulated = true } if j.opts.indent != "" { j.MarshalOptions.Indent = j.opts.indent } if j.opts.allowPartial { j.MarshalOptions.AllowPartial = true j.UnmarshalOptions.AllowPartial = true } if j.opts.discardUnknown { j.UnmarshalOptions.DiscardUnknown = true } return j } func (j *JSONPb) Marshal(v interface{}) ([]byte, error) { return j.JSONPb.Marshal(v) } func (j *JSONPb) MarshaToStructpb(v interface{}) (*structpb.Struct, error) { var jb []byte switch v := v.(type) { case nil: return &structpb.Struct{}, nil case *structpb.Struct: return v, nil case proto.Message: data, err := j.JSONPb.Marshal(v) if err != nil { return nil, fmt.Errorf("failed to Marshal json: %v", err) } jb = []byte(data) case []byte: jb = v case *[]byte: jb = *v case string: jb = []byte(v) case *string: jb = []byte(*v) default: var err error jb, err = json.Marshal(v) if err != nil { return nil, fmt.Errorf("failed to Marshal json: %v", err) } } var dataStructpb structpb.Struct if err := j.JSONPb.Unmarshal(jb, &dataStructpb); err != nil { return nil, err } return &dataStructpb, nil } /* // if implemet the function, can parse some field from req data func (j *JSONPb) NewDecoder(r io.Reader) runtime.Decoder { return runtime.DecoderFunc(func(v interface{}) error { rawData, err := ioutil.ReadAll(r) if err != nil { return err } err = j.JSONPb.Unmarshal(rawData, v) if err != nil { return err } id := reflect_.RetrieveId(v, reflect_.FieldNameRequestId) _ = id return nil }) } */ ================================================ FILE: go/runtime/marshaler/jsonpb.marshaler.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 marshaler func WithUseProtoNames(useProtoNames bool) JSONPbOption { return JSONPbOptionFunc(func(c *JSONPb) { c.opts.useProtoNames = useProtoNames }) } func WithUseEnumNumbers(useEnumNumbers bool) JSONPbOption { return JSONPbOptionFunc(func(c *JSONPb) { c.opts.useEnumNumbers = useEnumNumbers }) } func WithEmitUnpopulated(emitUnpopulated bool) JSONPbOption { return JSONPbOptionFunc(func(c *JSONPb) { c.opts.emitUnpopulated = emitUnpopulated }) } func WithDiscardUnknown(discardUnknown bool) JSONPbOption { return JSONPbOptionFunc(func(c *JSONPb) { c.opts.discardUnknown = discardUnknown }) } func WithIndent(indent string) JSONPbOption { return JSONPbOptionFunc(func(c *JSONPb) { c.opts.indent = indent }) } func WithAllowPartial(allowPartial bool) JSONPbOption { return JSONPbOptionFunc(func(c *JSONPb) { c.opts.allowPartial = allowPartial }) } ================================================ FILE: go/runtime/marshaler/jsonpb.marshaler_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 marshaler // A JSONPbOption sets options. type JSONPbOption interface { apply(*JSONPb) } // EmptyJSONPbOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyJSONPbOption struct{} func (EmptyJSONPbOption) apply(*JSONPb) {} // JSONPbOptionFunc wraps a function that modifies Client into an // implementation of the JSONPbOption interface. type JSONPbOptionFunc func(*JSONPb) func (f JSONPbOptionFunc) apply(do *JSONPb) { f(do) } // sample code for option, default for nothing to change func _JSONPbOptionWithDefault() JSONPbOption { return JSONPbOptionFunc(func(*JSONPb) { // nothing to change }) } func (o *JSONPb) ApplyOptions(options ...JSONPbOption) *JSONPb { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/runtime/marshaler/proto.marshaler.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 marshaler import ( "github.com/gin-gonic/gin/binding" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" ) // ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes type ProtoMarshaller struct { runtime.ProtoMarshaller } // ContentType always returns "application/x-protobuf". func (*ProtoMarshaller) ContentType(_ interface{}) string { return binding.MIMEPROTOBUF } ================================================ FILE: go/runtime/meta.data.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime import ( "context" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" ) func GetMetadata(ctx context.Context, key string) []string { md, ok := runtime.ServerMetadataFromContext(ctx) if !ok || md.HeaderMD == nil { return nil } return md.HeaderMD.Get(key) } ================================================ FILE: go/runtime/panic.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime import ( "fmt" "net/http" "github.com/sirupsen/logrus" ) // PanicHandlers is a list of functions which will be invoked when a panic happens. var PanicHandlers = []func(interface{}){logPanic} //must use defer Recover() //not effective for calling defer func() {Recover()}() func Recover() { if r := recover(); r != nil { for _, fn := range PanicHandlers { fn(r) } } } // logPanic logs the caller tree when a panic occurs (except in the special case of http.ErrAbortHandler). func logPanic(r interface{}) { if r == http.ErrAbortHandler { // honor the http.ErrAbortHandler sentinel panic value: // ErrAbortHandler is a sentinel panic value to abort a handler. // While any panic from ServeHTTP aborts the response to the client, // panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log. return } // Same as stdlib http server code. Manually allocate stack trace buffer size // to prevent excessively large logs stacktrace := GetCallStackTrace() if _, ok := r.(string); ok { logrus.Errorf("Observed a panic: %s\n%s", r, stacktrace) } else { logrus.Errorf("Observed a panic: %#v (%v)\n%s", r, r, stacktrace) } } // RecoverFromPanic replaces the specified error with an error containing the // original error, and the call tree when a panic occurs. This enables error // handlers to handle errors and panics the same way. func RecoverFromPanic(err *error) { if r := recover(); r != nil { // Same as stdlib http server code. Manually allocate stack trace buffer size // to prevent excessively large logs stacktrace := GetCallStackTrace() *err = fmt.Errorf( "recovered from panic %q. (err=%v) Call stack:\n%s", r, *err, stacktrace) } } // Must panics on non-nil errors. Useful to handling programmer level errors func Must(err error) { if err != nil { panic(err) } } ================================================ FILE: go/runtime/panic_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime_test import ( "testing" runtime_ "github.com/kaydxh/golang/go/runtime" ) func TestRecover(t *testing.T) { defer runtime_.Recover() panic("test panic") } func testRecoverFromPanic() (err error) { defer runtime_.RecoverFromPanic(&err) panic("test panic") } func TestRecoverFromPanic(t *testing.T) { err := testRecoverFromPanic() t.Logf("err: %v", err) } ================================================ FILE: go/runtime/stack.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 runtime import ( "bytes" "errors" "fmt" "os" "runtime/debug" "strings" ) func FormatStack() ([]byte, error) { debugStack := debug.Stack() return prettyStack{}.parse(debugStack) } type prettyStack struct { } func (s prettyStack) parse(debugStack []byte) ([]byte, error) { var err error buf := &bytes.Buffer{} fmt.Fprintf(buf, "\n") fmt.Fprintf(buf, " panic: ") fmt.Fprintf(buf, "\n") // process debug stack info stack := strings.Split(string(debugStack), "\n") lines := []string{} // locate panic line, as we may have nested panics for i := len(stack) - 1; i > 0; i-- { lines = append(lines, stack[i]) if strings.HasPrefix(stack[i], "panic(") { lines = lines[0 : len(lines)-2] // remove boilerplate break } } // reverse for i := len(lines)/2 - 1; i >= 0; i-- { opp := len(lines) - 1 - i lines[i], lines[opp] = lines[opp], lines[i] } // decorate for i, line := range lines { lines[i], err = s.decorateLine(line, i) if err != nil { return nil, err } } for _, l := range lines { fmt.Fprintf(buf, "%s", l) } return buf.Bytes(), nil } func (s prettyStack) decorateLine(line string, num int) (string, error) { line = strings.TrimSpace(line) if strings.HasPrefix(line, "\t") || strings.Contains(line, ".go:") { return s.decorateSourceLine(line, num) } else if strings.HasSuffix(line, ")") { return s.decorateFuncCallLine(line, num) } else { if strings.HasPrefix(line, "\t") { return strings.Replace(line, "\t", " ", 1), nil } else { return fmt.Sprintf(" %s\n", line), nil } } } func (s prettyStack) decorateFuncCallLine(line string, num int) (string, error) { idx := strings.LastIndex(line, "(") if idx < 0 { return "", errors.New("not a func call line") } buf := &bytes.Buffer{} pkg := line[0:idx] // addr := line[idx:] method := "" if idx := strings.LastIndex(pkg, string(os.PathSeparator)); idx < 0 { if idx := strings.Index(pkg, "."); idx > 0 { method = pkg[idx:] pkg = pkg[0:idx] } } else { method = pkg[idx+1:] pkg = pkg[0 : idx+1] if idx := strings.Index(method, "."); idx > 0 { pkg += method[0:idx] method = method[idx:] } } if num == 0 { fmt.Fprintf(buf, " -> ") } else { fmt.Fprintf(buf, " ") } fmt.Fprintf(buf, "%s", pkg) fmt.Fprintf(buf, "%s\n", method) return buf.String(), nil } func (s prettyStack) decorateSourceLine(line string, num int) (string, error) { idx := strings.LastIndex(line, ".go:") if idx < 0 { return "", errors.New("not a source line") } buf := &bytes.Buffer{} path := line[0 : idx+3] lineno := line[idx+3:] idx = strings.LastIndex(path, string(os.PathSeparator)) dir := path[0 : idx+1] file := path[idx+1:] idx = strings.Index(lineno, " ") if idx > 0 { lineno = lineno[0:idx] } if num == 1 { fmt.Fprintf(buf, " -> ") } else { fmt.Fprintf(buf, " ") } fmt.Fprintf(buf, "%s", dir) fmt.Fprintf(buf, "%s", file) fmt.Fprintf(buf, "%s", lineno) if num == 1 { fmt.Fprintf(buf, "\n") } fmt.Fprintf(buf, "\n") return buf.String(), nil } ================================================ FILE: go/slices/slices.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 slices import ( set_ "github.com/kaydxh/golang/go/container/set" "golang.org/x/exp/slices" ) func Unique[S ~[]E, E comparable](s S) S { ss := set_.New[E]() for _, v := range s { ss.Insert(v) } return ss.List() } func SliceIntersection[S ~[]E, E comparable](s1, s2 S) S { ss1 := set_.New[E]() for _, s := range s1 { ss1.Insert(s) } ss2 := set_.New[E]() for _, s := range s2 { ss2.Insert(s) } var ss S for _, v := range ss1.Intersection(ss2).List() { ss = append(ss, v) } return ss } func SliceDifference[S ~[]E, E comparable](s1, s2 S) S { ss1 := set_.New[E]() for _, s := range s1 { ss1.Insert(s) } ss2 := set_.New[E]() for _, s := range s2 { ss2.Insert(s) } var ss S for _, v := range ss1.Difference(ss2).List() { ss = append(ss, v) } return ss } func SliceWithCondition[S ~[]E, E comparable](s1 S, cond func(e E) bool) S { ss1 := set_.New[E]() for _, s := range s1 { if cond(s) { ss1.Insert(s) } } var ss S for _, v := range ss1.List() { ss = append(ss, v) } return ss } func FirstOrDefaultZero[S ~[]E, E comparable](s S) E { var zeroE E cond := func(e E) bool { return e != zeroE } i := slices.IndexFunc(s, cond) if i == -1 { return zeroE } return s[i] } func RemoveEmpty[S ~[]E, E comparable](s S) S { var ss S var zero E for _, v := range s { if v != zero { ss = append(ss, v) } } return ss } ================================================ FILE: go/slices/slices_test.go ================================================ package slices_test import ( "fmt" "testing" slices_ "github.com/kaydxh/golang/go/slices" ) func TestSliceIntersection(t *testing.T) { testCases := []struct { name string s1 []string s2 []string expected []string }{ { name: "test string", s1: []string{"1", "2", "3", "4"}, s2: []string{"3", "4", "5", "6"}, expected: []string{"3", "4"}, }, { name: "test string2", s1: []string{"1", "2", "3", "4"}, s2: []string{"5", "6"}, expected: []string{}, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { intersection := slices_.SliceIntersection(testCase.s1, testCase.s2) if len(intersection) != len(testCase.expected) { t.Fatalf("Expected Intersection len: %v, got : %v", len(testCase.expected), len(intersection)) } t.Logf("intersection :%v", intersection) }) } } func TestSliceDifference(t *testing.T) { testCases := []struct { name string s1 []string s2 []string expected []string }{ { name: "test string", s1: []string{"1", "2", "3", "4"}, s2: []string{"3", "4", "5", "6"}, expected: []string{"1", "2"}, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { difference := slices_.SliceDifference(testCase.s1, testCase.s2) if len(difference) != len(testCase.expected) { t.Fatalf("Expected Difference len: %v, got : %v", len(testCase.expected), len(difference)) } t.Logf("difference :%v", difference) }) } } func TestRemoveEmpty(t *testing.T) { testCases := []struct { s []string }{ { s: []string{"1", "", "3", "4"}, }, { s: []string{"", "", "", ""}, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { intersection := slices_.RemoveEmpty(testCase.s) t.Logf("intersection :%v", intersection) }) } } func TestFirstOrDefaultZero(t *testing.T) { testCases := []struct { s []string }{ { s: []string{"1", "", "3", "4"}, }, { s: []string{"", "", "", "2"}, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { intersection := slices_.FirstOrDefaultZero(testCase.s) t.Logf("FirstOrDefaultZero :%v", intersection) }) } } ================================================ FILE: go/strconv/atoi.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strconv import ( "strconv" ) func ParseUintOrFallback(s string, base int, bitSize int, defaultValue uint64) (uint64, error) { ns, err := strconv.ParseUint(s, base, bitSize) if err != nil { return defaultValue, err } return ns, nil } func ParseInt64Batch(m map[string]string) (map[string]int64, error) { nm := make(map[string]int64, 0) for k, v := range m { ns, err := strconv.ParseInt(v, 10, 64) if err != nil { return nil, err } nm[k] = ns } return nm, nil } ================================================ FILE: go/strconv/atoi_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strconv_test import ( "fmt" "testing" strconv_ "github.com/kaydxh/golang/go/strconv" "gotest.tools/v3/assert" ) func TestParseInt64Batch(t *testing.T) { m := map[string]string{ "fileId": "12345", "partId": "1", } nm, err := strconv_.ParseInt64Batch(m) if err != nil { t.Errorf("expect nil, got %v", err) } assert.Equal(t, nm["fileId"], int64(12345)) assert.Equal(t, nm["partId"], int64(1)) fmt.Println(nm) } ================================================ FILE: go/strconv/atonum.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strconv import ( "fmt" "strconv" ) func ToFloat(str string) (float64, error) { return strconv.ParseFloat(str, 64) } func ToInt(str string) (int, error) { return strconv.Atoi(str) } func ToInt64(str string) (int64, error) { return strconv.ParseInt(str, 10, 64) } func ToUInt64(str string) (uint64, error) { return strconv.ParseUint(str, 10, 64) } func ParseNumOrDefault[T any](str string, _default T, convert func(string) (T, error)) T { if str == "" { return _default } n, err := convert(str) if err != nil { //logurs.Infof("Invalid number value: %s", err) return _default } return n } func ParseNum[T any](str string, convert func(string) (T, error)) (T, error) { var t T if str == "" { return t, fmt.Errorf("string is empty") } return convert(str) } func ParseNums[T any](strs []string, convert func(string) (T, error)) ([]T, error) { var ts []T if len(strs) == 0{ return ts, fmt.Errorf("string is empty") } for _, str := range strs { t, err := convert(str) if err != nil { return nil, err } ts = append(ts, t) } return ts, nil } ================================================ FILE: go/strconv/atonum_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strconv_test import ( "fmt" "testing" strconv_ "github.com/kaydxh/golang/go/strconv" ) func TestParseNumOrDefault(t *testing.T) { testCases := []struct { str string expected string }{ { str: "12345", expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { num := strconv_.ParseNumOrDefault(testCase.str, 0, strconv_.ToInt) t.Logf("get num: %v", num) }) } } func TestParseNum(t *testing.T) { testCases := []struct { str string expected string }{ { str: "12345", expected: "", }, { str: "badcase", expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { num, err := strconv_.ParseNum(testCase.str, strconv_.ToInt) if err != nil { t.Errorf("expecet nil, got %v", err) } t.Logf("get num: %v", num) }) } } func TestParseNums(t *testing.T) { testCases := []struct { strs []string expected string }{ { strs: []string{"12345"}, expected: "", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { nums, err := strconv_.ParseNums(testCase.strs, strconv_.ToInt) if err != nil { t.Errorf("expecet nil, got %v", err) } t.Logf("get nums: %v", nums) }) } } ================================================ FILE: go/strconv/itoa.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strconv ================================================ FILE: go/strings/string_slice.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strings import ( "strings" set_ "github.com/kaydxh/golang/go/container/set" ) func SliceUnique(s ...string) []string { ss := set_.NewString() for _, v := range s { ss.Insert(v) } return ss.List() } func SliceIntersection(s1 []string, s2 []string) []string { ss1 := set_.NewObject() for _, s := range s1 { ss1.Insert(s) } ss2 := set_.NewObject() for _, s := range s2 { ss2.Insert(s) } ss := []string{} for _, v := range ss1.Intersection(ss2).List() { s, ok := v.(string) if ok { ss = append(ss, s) } } return ss } func SliceDifference(s1 []string, s2 []string) []string { ss1 := set_.NewObject() for _, s := range s1 { ss1.Insert(s) } ss2 := set_.NewObject() for _, s := range s2 { ss2.Insert(s) } ss := []string{} for _, v := range ss1.Difference(ss2).List() { s, ok := v.(string) if ok { ss = append(ss, s) } } return ss } func SliceWithCondition(s1 []string, cond func(s2 string) bool) []string { ss1 := set_.NewObject() for _, s := range s1 { if cond(s) { ss1.Insert(s) } } ss := []string{} for _, v := range ss1.List() { s, ok := v.(string) if ok { ss = append(ss, s) } } return ss } func RemoveEmpty(s []string) []string { var ss []string for _, v := range s { if v != "" { ss = append(ss, v) } } return ss } // sliceContains reports whether the provided string is present in the given slice of strings. func SliceContainsCaseInSensitive(list []string, target string) bool { return SliceContains(list, target, false) } func SliceContains(list []string, target string, caseSensitive bool) bool { if !caseSensitive { target = strings.ToLower(target) } for _, s := range list { if !caseSensitive { s = strings.ToLower(s) } if s == target { return true } } return false } /* func SliceIntersectionInt(s1 []int, s2 []int) []int { ss1 := set_.NewObject(set_.GenerateArray([...]int(s1...))) for _, s := range s1 { ss1.Insert(s) } ss2 := set_.NewObject() for _, s := range s2 { ss2.Insert(s) } ss := []string{} for _, v := range ss1.Intersection(ss2).List() { s, ok := v.(string) if ok { ss = append(ss, s) } } return ss } */ func Filter(ss []string, cond func(string) bool) []string { var res []string for _, s := range ss { if cond(s) { res = append(res, s) } } return res } ================================================ FILE: go/strings/string_slice_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strings_test import ( "fmt" "testing" strings_ "github.com/kaydxh/golang/go/strings" "github.com/stretchr/testify/assert" ) func TestStringIntersection(t *testing.T) { testCases := []struct { name string s1 []string s2 []string expected []string }{ { name: "test string", s1: []string{"1", "2", "3", "4"}, s2: []string{"3", "4", "5", "6"}, expected: []string{"3", "4"}, }, { name: "test string2", s1: []string{"1", "2", "3", "4"}, s2: []string{"5", "6"}, expected: []string{}, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { intersection := strings_.SliceIntersection(testCase.s1, testCase.s2) if len(intersection) != len(testCase.expected) { t.Fatalf("Expected Intersection len: %v, got : %v", len(testCase.expected), len(intersection)) } t.Logf("intersection :%v", intersection) }) } } func TestSliceDifference(t *testing.T) { testCases := []struct { name string s1 []string s2 []string expected []string }{ { name: "test string", s1: []string{"1", "2", "3", "4"}, s2: []string{"3", "4", "5", "6"}, expected: []string{"1", "2"}, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { difference := strings_.SliceDifference(testCase.s1, testCase.s2) if len(difference) != len(testCase.expected) { t.Fatalf("Expected Difference len: %v, got : %v", len(testCase.expected), len(difference)) } t.Logf("difference :%v", difference) }) } } func TestRemoveEmpty(t *testing.T) { testCases := []struct { s []string }{ { s: []string{"1", "", "3", "4"}, }, { s: []string{"", "", "", ""}, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { intersection := strings_.RemoveEmpty(testCase.s) t.Logf("intersection :%v", intersection) }) } } func TestSliceContains(t *testing.T) { testCases := []struct { s []string target string caseSensitive bool expected bool }{ { s: []string{"a", "bdx"}, target: "bDx", caseSensitive: false, expected: true, }, { s: []string{"a", "bdx"}, target: "bdx", caseSensitive: true, expected: true, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { has := strings_.SliceContains(testCase.s, testCase.target, testCase.caseSensitive) t.Logf("has :%v", has) assert.Equal(t, testCase.expected, has) }) } } func TestFilter(t *testing.T) { testCases := []struct { s []string cond func(string) bool expected []string }{ { s: []string{"a", "bdx"}, cond: func(s string) bool { return s == "a" }, expected: []string{"a"}, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { result := strings_.Filter(testCase.s, testCase.cond) t.Logf("result:%v", result) assert.Equal(t, testCase.expected, result) }) } } ================================================ FILE: go/strings/strings.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strings import ( "fmt" "strings" "unicode/utf8" strconv_ "github.com/kaydxh/golang/go/strconv" ) func GetStringOrFallback(values ...string) string { for _, v := range values { if v != "" { return v } } return "" } /* func Replace(s string, old string, news []string, n int) string { if len(news) == 0 || n == 0 { return s } if m := strings.Count(s, old); m == 0 { return s // avoid allocation } else if n < 0 || m < n { n = m } // if len(news) < n , padding news use last element in news for i := 0; i < n-len(news); i++ { news = append(news, news[len(news)-1]) } incLen := 0 for i := 0; i < n; i++ { incLen += len(news[i]) - len(old) } // Apply replacements to buffer. var b strings.Builder b.Grow(len(s) + incLen) start := 0 for i := 0; i < n; i++ { j := start if len(old) == 0 { if i > 0 { _, wid := utf8.DecodeRuneInString(s[start:]) j += wid } } else { j += strings.Index(s[start:], old) } b.WriteString(s[start:j]) b.WriteString(news[i]) start = j + len(old) } b.WriteString(s[start:]) return b.String() } */ /* func ReplaceAll(s, old string, news []string) string { return Replace(s, old, news, -1) } */ func Replace(s string, old string, news []interface{}, useQuote bool, n int) string { if len(news) == 0 || n == 0 { return s } if m := strings.Count(s, old); m == 0 { return s // avoid allocation } else if n < 0 || m < n { n = m } // if len(news) < n , padding news use last element in news for i := 0; i < n-len(news); i++ { news = append(news, news[len(news)-1]) } var b strings.Builder start := 0 for i := 0; i < n; i++ { j := start if len(old) == 0 { if i > 0 { _, wid := utf8.DecodeRuneInString(s[start:]) j += wid } } else { j += strings.Index(s[start:], old) } b.WriteString(s[start:j]) if useQuote { b.WriteString(fmt.Sprintf(`"%v"`, news[i])) } else { b.WriteString(fmt.Sprintf("%v", news[i])) } start = j + len(old) } b.WriteString(s[start:]) return b.String() } func ReplaceAll(s, old string, news []interface{}, useQuote bool) string { return Replace(s, old, news, useQuote, -1) } // Split slices s into all substrings separated by sep and returns a slice of // the substrings between those separators. // // If s does not contain sep and sep is not empty, Split returns a // slice of length 0. // // If sep is empty, Split splits after each UTF-8 sequence. If both s // and sep are empty, Split returns an empty slice. // // It is equivalent to SplitN with a count of -1. func SplitOmitEmpty(s, sep string) []string { var res []string a := strings.Split(s, sep) for _, v := range a { if v != "" { res = append(res, v) } } return res } // Split2 returns the values from strings.SplitN(s, sep, 2). // If sep is not found, it returns ("", "", false) instead. func Split2(s, sep string) (string, string, bool) { spl := strings.SplitN(s, sep, 2) if len(spl) < 2 { return "", "", false } return spl[0], spl[1], true } func SplitToNums[T any](s, sep string, convert func(string) (T, error)) ([]T, error) { ss := SplitOmitEmpty(s, sep) return strconv_.ParseNums(ss, convert) } func EqualCaseInsensitive(src, dst string) bool { return strings.ToLower(src) == strings.ToLower(dst) } func EmptyString(str string) bool { return strings.TrimSpace(str) == "" } ================================================ FILE: go/strings/strings_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 strings_test import ( "fmt" "strings" "testing" strconv_ "github.com/kaydxh/golang/go/strconv" strings_ "github.com/kaydxh/golang/go/strings" "github.com/stretchr/testify/assert" ) func TestReplace(t *testing.T) { testCases := []struct { s string old string news []interface{} n int expected string }{ { s: "task_id in (?)", old: "?", news: []interface{}{"a"}, n: 1, expected: `task_id in ("a")`, }, { s: "task_id in (?, ?, ?, ?, ?)", old: "?", news: []interface{}{"a", "a", "a", "a"}, n: 5, expected: `task_id in ("a", "a", "a", "a", "a")`, }, } for _, testCase := range testCases { t.Run(testCase.s, func(t *testing.T) { newStr := strings_.Replace(testCase.s, testCase.old, testCase.news, true, testCase.n) t.Logf("newStr: %v", newStr) assert.Equal(t, testCase.expected, newStr) }) } } func TestReplaceAll(t *testing.T) { testCases := []struct { s string old string news []interface{} expected string }{ { s: "task_id in (?)", old: "?", news: []interface{}{"a"}, expected: `task_id in ("a")`, }, { s: "task_id in (?, ?, ?, ?, ?)", old: "?", news: []interface{}{"a", "a", "a", "a"}, expected: `task_id in ("a", "a", "a", "a", "a")`, }, } for _, testCase := range testCases { t.Run(testCase.s, func(t *testing.T) { newStr := strings_.ReplaceAll(testCase.s, testCase.old, testCase.news, true) t.Logf("newStr: %v", newStr) assert.Equal(t, testCase.expected, newStr) }) } } func TestSplit(t *testing.T) { testCases := []struct { s string sep string }{ { s: "1", sep: ",", }, { s: "a,b,c", sep: ",", }, { s: "a,b,c,,,,,", sep: ",", }, } for _, testCase := range testCases { t.Run(testCase.s, func(t *testing.T) { ss := strings_.SplitOmitEmpty(testCase.s, testCase.sep) t.Logf("ss: %v. len(ss): %v", ss, len(ss)) }) } } func TestSplitToNums(t *testing.T) { testCases := []struct { s string sep string }{ { s: "1,2,3,4", sep: ",", }, { s: "1,2,3,4,", sep: ",", }, { s: "1,2,3,4,a", sep: ",", }, } for _, testCase := range testCases { t.Run(testCase.s, func(t *testing.T) { nums, err := strings_.SplitToNums(testCase.s, testCase.sep, strconv_.ToInt64) if err != nil { t.Errorf("failed to split to nums, err: %v", err) return } t.Logf("got nums %v", nums) }) } } func TestGetStringOrFallback(t *testing.T) { type args struct { value string defaultValue string } tests := []struct { name string args args want string }{ // TODO: Add test cases. { name: "test1", args: args{ value: "abc", defaultValue: "default", }, want: "abc", }, { name: "test2", args: args{ value: "", defaultValue: "default", }, want: "default", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := strings_.GetStringOrFallback(tt.args.value, tt.args.defaultValue); got != tt.want { t.Errorf("GetStringOrFallback() = %v, want %v", got, tt.want) } }) } } func TestLastIndex(t *testing.T) { tests := []struct { value string tag string }{ // TODO: Add test cases. { value: "abc_fashion_0", tag: "_fashion", }, } for i, tt := range tests { t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { index := strings.LastIndex(tt.value, tt.tag) if index != -1 { t.Logf("result: %v", tt.value[:index]) } else { t.Logf("result: %v", tt.value) } }) } } ================================================ FILE: go/sync/atomic/file_lock.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 atomic import ( "fmt" "os" "path/filepath" "strings" os_ "github.com/kaydxh/golang/go/os" ) type FileLock string func (m *FileLock) TryLock() error { if m == nil { return fmt.Errorf("nil pointer") } if *m == "" { return fmt.Errorf("invalid file") } name := string(*m) if !strings.HasSuffix(name, ".lock") { *m += ".lock" } dir := filepath.Dir(name) err := os_.MakeDirAll(dir) if err != nil { return err } f, err := os.OpenFile(string(*m), os.O_CREATE|os.O_EXCL, 0600) if err != nil { return err } return f.Close() } func (m *FileLock) TryUnLock() error { if m == nil || *m == "" { return nil } return os.Remove(string(*m)) } /* func makePidFile(name string) (tmpname string, cleanup func(), err error) { tmplock, err := ioutil.TempFile( filepath.Dir(name), filepath.Base(name)+fmt.Sprintf("%d", os.GetPid())+".lock", ) if err != nil { return "", nil, err } cleanup = func() { _ = tmplock.Close() _ = os.Remove(tmplock.Name()) } } */ ================================================ FILE: go/sync/atomic/file_lock_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 atomic_test import ( "testing" "github.com/kaydxh/golang/go/sync/atomic" atomic_ "github.com/kaydxh/golang/go/sync/atomic" ) func TestTryLock(t *testing.T) { var mu atomic_.FileLock = atomic.FileLock("test_lockfile") err := mu.TryLock() if err != nil { t.Errorf("expect nil, got %v", err) return } err = mu.TryUnLock() if err != nil { t.Errorf("expect nil, got %v", err) return } return } ================================================ FILE: go/sync/cond.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 sync import ( "fmt" "sync" "sync/atomic" "time" "unsafe" ) // Cond 条件变量不保证顺序性,即signal只是通知wait去获取数据,wait拿到的数据是不是 // signal当时给的数据,不能保证 type Cond struct { L sync.Locker ch chan struct{} checker copyChecker noCopy noCopy } func NewCond(l sync.Locker) *Cond { c := &Cond{ L: l, ch: make(chan struct{}), } return c } func (c *Cond) wait() { c.checker.check() c.L.Unlock() defer c.L.Lock() <-c.ch } func (c *Cond) waitFor(timeout time.Duration) error { c.L.Unlock() defer c.L.Lock() select { case <-c.ch: return nil case <-time.After(timeout): return fmt.Errorf("wait timeout: %v\n", timeout) } } func (c *Cond) WaitForDo(timeout time.Duration, pred func() bool, do func() error) error { c.checker.check() c.L.Lock() defer c.L.Unlock() for !pred() { start := time.Now() err := c.waitFor(timeout) if err != nil { return err } timeout -= time.Now().Sub(start) } if do != nil { do() } return nil } func (c *Cond) WaitUntil(pred func() bool) { c.checker.check() c.WaitUntilDo(pred, func() error { return nil }) } func (c *Cond) WaitUntilDo(pred func() bool, do func() error) { c.checker.check() for { err := c.WaitForDo(5*time.Second, pred, do) if err == nil { break } } } func (c *Cond) SignalDo(do func() error) { c.L.Lock() if do != nil { do() } c.L.Unlock() c.Signal() } func (c *Cond) BroadcastDo(do func() error) { c.L.Lock() if do != nil { do() } c.L.Unlock() c.Broadcast() } func (c *Cond) Signal() { c.checker.check() go func() { select { case c.ch <- struct{}{}: default: } }() } func (c *Cond) Broadcast() { c.checker.check() go func() { close(c.ch) c.ch = make(chan struct{}) }() } // copyChecker holds back pointer to itself to detect object copying. type copyChecker uintptr func (c *copyChecker) check() { if uintptr(*c) != uintptr(unsafe.Pointer(c)) && !atomic.CompareAndSwapUintptr((*uintptr)(c), 0, uintptr(unsafe.Pointer(c))) && uintptr(*c) != uintptr(unsafe.Pointer(c)) { panic("sync.Cond is copied") } } // noCopy may be embedded into structs which must not be copied // after the first use. // // See https://golang.org/issues/8005#issuecomment-190753527 // for details. type noCopy struct{} // Lock is a no-op used by -copylocks checker from `go vet`. func (*noCopy) Lock() {} func (*noCopy) Unlock() {} ================================================ FILE: go/sync/cond_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 sync_test import ( "fmt" "sync" "testing" "time" sync_ "github.com/kaydxh/golang/go/sync" "github.com/stretchr/testify/assert" ) func TestWaitForDo(t *testing.T) { assert := assert.New(t) l := new(sync.Mutex) cond := sync_.NewCond(l) a := 5 timout := 4 * time.Second var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() err := cond.WaitForDo(timout, func() bool { fmt.Printf("==>a = %v\n", a) return a == 3 }, func() error { a += 100 fmt.Printf("a: %v\n", a) assert.Equal(103, a) return nil }) assert.Equal(nil, err) }() go func() { for { cond.SignalDo(func() error { a-- //this sleep can increase the probability to waitforDo //miss condition = > a==3 time.Sleep(1 * time.Second) fmt.Printf("a: %v\n", a) return nil }) //time.Sleep(1 * time.Second) } }() wg.Wait() } // condion only be fit for range condition func TestWaitUntilDo(t *testing.T) { assert := assert.New(t) l := new(sync.Mutex) cond := sync_.NewCond(l) a := 5 var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() cond.WaitUntilDo(func() bool { fmt.Printf("==>a = %v\n", a) return a < 0 }, func() error { fmt.Printf("a: %v\n", a) assert.LessOrEqual(a, 0) return nil }) }() go func() { for { cond.SignalDo(func() error { a-- //this sleep can increase the probability to waitforDo //miss condition = > a==3 time.Sleep(1 * time.Second) fmt.Printf("a: %v\n", a) return nil }) //time.Sleep(1 * time.Second) } }() wg.Wait() } func TestBroadCast(t *testing.T) { assert := assert.New(t) l := new(sync.Mutex) cond := sync_.NewCond(l) initValue := 10 expected := 3 threads := 5 var wg sync.WaitGroup for i := 0; i < threads; i++ { wg.Add(1) go func() { defer wg.Done() cond.WaitForDo(10*time.Second, func() bool { return expected == initValue }, func() error { assert.Equal(initValue, expected) t.Logf("wait done") return nil }) }() } go func() { for { time.Sleep(time.Second) cond.BroadcastDo(func() error { initValue-- t.Logf("init: %v\n", initValue) return nil }) } }() wg.Wait() } ================================================ FILE: go/syscall/disk.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 syscall import ( "syscall" ) type DiskUsage struct { stat *syscall.Statfs_t } // NewDiskUsage 直接对目标路径调用 syscall.Statfs 获取磁盘使用信息, // 兼容 Linux 和 macOS(不再依赖 /proc/self/mountinfo)。 func NewDiskUsage(path string) (*DiskUsage, error) { var stat syscall.Statfs_t err := syscall.Statfs(path, &stat) if err != nil { return nil, err } return &DiskUsage{&stat}, nil } // Free returns total free bytes on file system func (du *DiskUsage) Free() uint64 { return du.stat.Bfree * uint64(du.stat.Bsize) } // Avail returns total avail bytes on file system func (du *DiskUsage) Avail() uint64 { return du.stat.Bavail * uint64(du.stat.Bsize) } // Size returns total size of the file system func (du *DiskUsage) Size() uint64 { return uint64(du.stat.Blocks) * uint64(du.stat.Bsize) } // Size returns total used bytes on the file system func (du *DiskUsage) Used() uint64 { return du.Size() - du.Free() } // Usage returns percentage of used on the file system /* https://github.com/coreutils/coreutils/blob/master/src/df.c#:~:text=pct%20%3D%20u100%20/%20nonroot_total%20%2B%20(u100%20%25%20nonroot_total%20!%3D%200)%3B By default, ext2/3/4 filesystems reserve 5% of the space to be useable only by root. This is to avoid a normal user completely filling the disk which would then cause system components to fail whenever they next needed to write to the disk */ func (du *DiskUsage) Usage() float32 { var deta float32 u100 := du.Used() * 100 nonrootTotal := du.Used() + du.Avail() if u100%nonrootTotal != 0 { deta = 1.0 } return float32(u100)/float32(nonrootTotal) + deta } ================================================ FILE: go/syscall/disk_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 syscall_test import ( "testing" syscall_ "github.com/kaydxh/golang/go/syscall" ) // GOOS=linux GOARCH=amd64 go test -c disk_test.go -o test // /test -test.v func TestDiskUsage(t *testing.T) { testCases := []struct { volumePath string expected string }{ { volumePath: "/dev", expected: "", }, { volumePath: "/data", expected: "", }, { volumePath: "/data/home/log", expected: "", }, } for _, testCase := range testCases { t.Run(testCase.volumePath, func(t *testing.T) { du, err := syscall_.NewDiskUsage(testCase.volumePath) if err != nil { t.Errorf("new disk for path[%v] err, got : %s", testCase.volumePath, err) return } t.Logf( "disk free[%v], avali[%v], size[%v], used[%v], usage: %v", du.Free(), du.Avail(), du.Size(), du.Used(), du.Usage(), ) }) } } ================================================ FILE: go/syscall/memory_darwin.go ================================================ package syscall type MemoryUsage struct { } func (m MemoryUsage) SysTotalMemory() uint64 { return 0 } func (m MemoryUsage) SysFreeMemory() uint64 { return 0 } func (m MemoryUsage) SysUsageMemory() float64 { return 0 } ================================================ FILE: go/syscall/memory_linux.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 syscall import "syscall" // 其他实现可以参考https://github.com/shirou/gopsutil // /proc/meminfo // /proc/pid/status type MemoryUsage struct { } func (m MemoryUsage) SysTotalMemory() uint64 { in := &syscall.Sysinfo_t{} err := syscall.Sysinfo(in) if err != nil { return 0 } return uint64(in.Totalram) * uint64(in.Unit) } func (m MemoryUsage) SysFreeMemory() uint64 { in := &syscall.Sysinfo_t{} err := syscall.Sysinfo(in) if err != nil { return 0 } return uint64(in.Freeram) * uint64(in.Unit) } ================================================ FILE: go/syscall/memory_linux_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 syscall_test import ( "fmt" "testing" "time" syscall_ "github.com/kaydxh/golang/go/syscall" "github.com/shirou/gopsutil/mem" ) func TestSysTotalMemory(t *testing.T) { total := syscall_.MemoryUsage{}.SysTotalMemory() t.Logf("total: %vG", total/1024/1024/1024) free := syscall_.MemoryUsage{}.SysFreeMemory() t.Logf("free: %vG", free/1024/1024/1024) for { time.Sleep(time.Second) v, _ := mem.VirtualMemory() fmt.Printf( "Total: %v, Free:%v, UsedPercent:%f%%, Used:%v, Available: %v\n", v.Total, v.Free, v.UsedPercent, v.Used, v.Available, ) } } ================================================ FILE: go/syscall/rlimit.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 syscall import ( "fmt" "syscall" "golang.org/x/sys/unix" ) // SetNumFiles sets the linux rlimit for the maximum open files. func SetNumFiles(maxOpenFiles uint64) error { return unix.Setrlimit(unix.RLIMIT_NOFILE, &unix.Rlimit{Max: maxOpenFiles, Cur: maxOpenFiles}) } func GetNumFiles() (uint64, uint64, error) { var ( rlimit unix.Rlimit zero unix.Rlimit ) err := unix.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit) if err != nil { return 0, 0, err } if rlimit == zero { return 0, 0, fmt.Errorf("failed to get rlimit, got zero value: %#v", rlimit) } return rlimit.Cur, rlimit.Max, nil } func SetMaxNumFiles() (uint64, error) { _, maxOpenFiles, err := GetNumFiles() if err != nil { return 0, err } err = SetNumFiles(maxOpenFiles) if err != nil { return 0, err } newCurOpenFiles, _, err := GetNumFiles() if err != nil { return 0, err } if newCurOpenFiles != maxOpenFiles { return 0, fmt.Errorf("failed to set %d files, current open %v files", maxOpenFiles, newCurOpenFiles) } return newCurOpenFiles, nil } ================================================ FILE: go/syscall/rlimit_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 syscall_test import ( "testing" syscall_ "github.com/kaydxh/golang/go/syscall" ) func TestGetNumFiles(t *testing.T) { curOpenFiles, maxOpenFiles, err := syscall_.GetNumFiles() if err != nil { t.Fatalf("failed to get num files, err: %v", err) } t.Logf("curOpenFiles: %v, maxOpenFiles: %v", curOpenFiles, maxOpenFiles) } func TestSetMaxNumFiles(t *testing.T) { curOpenFiles, err := syscall_.SetMaxNumFiles() if err != nil { t.Fatalf("failed to set max num files, err: %v", err) } t.Logf("curOpenFiles: %v", curOpenFiles) } ================================================ FILE: go/syscall/syscall.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 syscall import ( "syscall" errors_ "github.com/kaydxh/golang/go/errors" ) func KillBatch(pids []int, sig syscall.Signal) (errorPids []int, err error) { var errs []error for _, pid := range pids { err = syscall.Kill(pid, sig) if err != nil { errorPids = append(errorPids, pid) errs = append(errs, err) } } return errorPids, errors_.NewAggregate(errs) } ================================================ FILE: go/time/backoff.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time import "time" type Backoff interface { NextBackOff() (time.Duration, bool) Reset() } ================================================ FILE: go/time/exponential_backoff.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time import ( "math/rand" "time" ) // Default values for ExponentialBackOff. const ( DefaultInitialInterval = 500 * time.Millisecond DefaultRandomizationFactor = 0.5 // The default multiplier value used for increment current interval DefaultMultiplier = 1.5 DefaultMaxInterval = 60 * time.Second DefaultMinInterval = DefaultInitialInterval DefaultMaxElapsedTime = 15 * time.Minute DefaultMaxElapsedCount = -1 ) type ExponentialBackOff struct { currentInterval time.Duration startTime time.Time elapsedCount int opts struct { InitialInterval time.Duration RandomizationFactor float64 Multiplier float64 MinInterval time.Duration MaxInterval time.Duration // After MaxElapsedTime the ExponentialBackOff returns Stop. // It never stops if MaxElapsedTime == 0. MaxElapsedTime time.Duration // It never stops if MaxElapsedCount == -1. MaxElapsedCount int //notes: when to stop deps on which condition come first, MaxElapsedTime or MaxElapsedCount } } func NewExponentialBackOff(opts ...ExponentialBackOffOption) *ExponentialBackOff { bo := &ExponentialBackOff{} bo.opts.InitialInterval = DefaultInitialInterval bo.opts.RandomizationFactor = DefaultRandomizationFactor bo.opts.Multiplier = DefaultMultiplier bo.opts.MaxInterval = DefaultMaxInterval bo.opts.MinInterval = DefaultMinInterval bo.opts.MaxElapsedTime = DefaultMaxElapsedTime bo.opts.MaxElapsedCount = DefaultMaxElapsedCount bo.ApplyOptions(opts...) bo.Reset() return bo } func (b *ExponentialBackOff) Reset() { b.currentInterval = b.opts.InitialInterval b.startTime = time.Now() } func (b *ExponentialBackOff) ResetWithInterval(initialInterval time.Duration) { b.currentInterval = initialInterval b.startTime = time.Now() } func (b *ExponentialBackOff) GetCurrentInterval() time.Duration { return b.currentInterval } // PreBackOff is get previos time duration // false : have gone over the maximu elapsed time // true : return remaining time func (b *ExponentialBackOff) PreBackOff() (time.Duration, bool) { nextRandomizedInterval, ok := b.validateAndGetNextInterval() if !ok { return nextRandomizedInterval, false } b.elapsedCount++ //update currentInterval b.decrementCurrentInterval() return nextRandomizedInterval, true } // NextBackOff is get next time duration func (b *ExponentialBackOff) NextBackOff() (time.Duration, bool) { b.elapsedCount++ nextRandomizedInterval, ok := b.validateAndGetNextInterval() if !ok { return nextRandomizedInterval, false } //update currentInterval b.incrementCurrentInterval() return nextRandomizedInterval, true } func (b *ExponentialBackOff) GetElapsedTime() time.Duration { return time.Now().Sub(b.startTime) } func (b *ExponentialBackOff) MaxElapsedTime() time.Duration { return b.opts.MaxElapsedTime } func (b *ExponentialBackOff) validateAndGetNextInterval() (time.Duration, bool) { elapsed := b.GetElapsedTime() nextRandomizedInterval := getRandomValueFromInterval(b.opts.RandomizationFactor, b.currentInterval) if b.opts.MaxElapsedTime > 0 && elapsed > b.opts.MaxElapsedTime { return nextRandomizedInterval, false } if b.opts.MaxElapsedCount > -1 && b.elapsedCount > b.opts.MaxElapsedCount { return nextRandomizedInterval, false } return nextRandomizedInterval, true } // Increment the current interval by multiplying it with the multiplier func (b *ExponentialBackOff) incrementCurrentInterval() { if b.opts.MaxInterval > 0 && time.Duration(float64(b.currentInterval)*b.opts.Multiplier) > b.opts.MaxInterval { b.currentInterval = b.opts.MaxInterval return } if b.opts.MinInterval > 0 && time.Duration(float64(b.currentInterval)*b.opts.Multiplier) < b.opts.MinInterval { b.currentInterval = b.opts.MinInterval return } b.currentInterval = time.Duration(float64(b.currentInterval) * b.opts.Multiplier) } // decrement the current interval by multiplying it with the multiplier func (b *ExponentialBackOff) decrementCurrentInterval() { if b.opts.MaxInterval > 0 && time.Duration(float64(b.currentInterval)*(1.0/b.opts.Multiplier)) > b.opts.MaxInterval { b.currentInterval = b.opts.MaxInterval return } if b.opts.MinInterval > 0 && time.Duration(float64(b.currentInterval)*(1.0/b.opts.Multiplier)) < b.opts.MinInterval { b.currentInterval = b.opts.MinInterval return } b.currentInterval = time.Duration(float64(b.currentInterval) * (1.0 / b.opts.Multiplier)) } func getRandomValueFromInterval( randomizationFactor float64, currentInterval time.Duration, ) time.Duration { var delta = randomizationFactor * float64(currentInterval) var minInterval = float64(currentInterval) - delta var maxInterval = float64(currentInterval) + delta // Get a random value from the range [minInterval, maxInterval]. // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then // we want a 33% chance for selecting either 1, 2 or 3. //Float64 returns, as a float64, a pseudo-random number in [0.0,1.0) //from the default Source. return time.Duration(minInterval + (rand.Float64() * (maxInterval - minInterval + 1))) } ================================================ FILE: go/time/exponential_backoff.options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time import "time" func WithExponentialBackOffOptionInitialInterval(initialInterval time.Duration) ExponentialBackOffOption { return ExponentialBackOffOptionFunc(func(opt *ExponentialBackOff) { opt.opts.InitialInterval = initialInterval }) } func WithExponentialBackOffOptionRandomizationFactor(randomizationFactor float64) ExponentialBackOffOption { return ExponentialBackOffOptionFunc(func(opt *ExponentialBackOff) { opt.opts.RandomizationFactor = randomizationFactor }) } func WithExponentialBackOffOptionMultiplier(multiplier float64) ExponentialBackOffOption { return ExponentialBackOffOptionFunc(func(opt *ExponentialBackOff) { opt.opts.Multiplier = multiplier }) } func WithExponentialBackOffOptionMaxInterval(maxInterval time.Duration) ExponentialBackOffOption { return ExponentialBackOffOptionFunc(func(opt *ExponentialBackOff) { opt.opts.MaxInterval = maxInterval }) } func WithExponentialBackOffOptionMinInterval(minInterval time.Duration) ExponentialBackOffOption { return ExponentialBackOffOptionFunc(func(opt *ExponentialBackOff) { opt.opts.MinInterval = minInterval }) } func WithExponentialBackOffOptionMaxElapsedTime(maxElapsedTime time.Duration) ExponentialBackOffOption { return ExponentialBackOffOptionFunc(func(opt *ExponentialBackOff) { opt.opts.MaxElapsedTime = maxElapsedTime }) } func WithExponentialBackOffOptionMaxElapsedCount(maxElapsedCount int) ExponentialBackOffOption { return ExponentialBackOffOptionFunc(func(opt *ExponentialBackOff) { opt.opts.MaxElapsedCount = maxElapsedCount }) } ================================================ FILE: go/time/exponential_backoff_options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time // A ExponentialBackOffOption sets options. type ExponentialBackOffOption interface { apply(*ExponentialBackOff) } // EmptyExponentialBackOffUrlOption does not alter the ExponentialBackOffuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyExponentialBackOffOption struct{} func (EmptyExponentialBackOffOption) apply(*ExponentialBackOff) {} // ExponentialBackOffOptionFunc wraps a function that modifies ExponentialBackOff into an // implementation of the ExponentialBackOffOption interface. type ExponentialBackOffOptionFunc func(*ExponentialBackOff) func (f ExponentialBackOffOptionFunc) apply(do *ExponentialBackOff) { f(do) } // sample code for option, default for nothing to change func _ExponentialBackOffOptionWithDefault() ExponentialBackOffOption { return ExponentialBackOffOptionFunc(func(*ExponentialBackOff) { // nothing to change }) } func (o *ExponentialBackOff) ApplyOptions(options ...ExponentialBackOffOption) *ExponentialBackOff { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: go/time/exponential_backoff_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time_test import ( "testing" "time" time_ "github.com/kaydxh/golang/go/time" "gotest.tools/assert" ) func TestExponentialBackOff(t *testing.T) { var ( testInitialInterval = 500 * time.Millisecond testRandomizationFactor = 0.1 testMultiplier = 2.0 testMaxInterval = 5 * time.Second testMaxElapsedTime = 15 * time.Minute testMaxElasedCount = 1 ) exp := time_.NewExponentialBackOff( time_.WithExponentialBackOffOptionInitialInterval(testInitialInterval), time_.WithExponentialBackOffOptionRandomizationFactor(testRandomizationFactor), time_.WithExponentialBackOffOptionMultiplier(testMultiplier), time_.WithExponentialBackOffOptionMaxInterval(testMaxInterval), time_.WithExponentialBackOffOptionMaxElapsedTime(testMaxElapsedTime), time_.WithExponentialBackOffOptionMaxElapsedCount(testMaxElasedCount), ) expectedResults := []time.Duration{500, 1000, 2000, 4000, 5000, 5000, 5000, 5000, 5000, 5000} for i, d := range expectedResults { expectedResults[i] = d * time.Millisecond } for _, expected := range expectedResults { assert.Equal(t, expected, exp.GetCurrentInterval()) // Assert that the next backoff falls in the expected range. var minInterval = expected - time.Duration(testRandomizationFactor*float64(expected)) var maxInterval = expected + time.Duration(testRandomizationFactor*float64(expected)) actualInterval, over := exp.NextBackOff() t.Logf("over: %v, actualInterval: %v", over, actualInterval) if !(minInterval <= actualInterval && actualInterval <= maxInterval) { t.Error("error") } } } func TestExponentialBackOffMaxElaspedTimeFailOver(t *testing.T) { var ( testInitialInterval = 500 * time.Millisecond testRandomizationFactor = 0.1 testMultiplier = 2.0 testMaxInterval = 5 * time.Second testMaxElapsedTime = 10 * time.Second ) exp := time_.NewExponentialBackOff( time_.WithExponentialBackOffOptionInitialInterval(testInitialInterval), time_.WithExponentialBackOffOptionRandomizationFactor(testRandomizationFactor), time_.WithExponentialBackOffOptionMultiplier(testMultiplier), time_.WithExponentialBackOffOptionMaxInterval(testMaxInterval), time_.WithExponentialBackOffOptionMaxElapsedTime(testMaxElapsedTime), ) expectedResults := []time.Duration{500, 1000, 2000, 4000, 5000, 5000, 5000, 5000, 5000, 5000} for i, d := range expectedResults { expectedResults[i] = d * time.Millisecond } for _, expected := range expectedResults { assert.Equal(t, expected, exp.GetCurrentInterval()) // Assert that the next backoff falls in the expected range. var minInterval = expected - time.Duration(testRandomizationFactor*float64(expected)) var maxInterval = expected + time.Duration(testRandomizationFactor*float64(expected)) actualInterval, over := exp.NextBackOff() t.Logf("over: %v, actualInterval: %v", over, actualInterval) if !(minInterval <= actualInterval && actualInterval <= maxInterval) { t.Error("error") } time.Sleep(actualInterval) } } func TestDescExponentialBackOff(t *testing.T) { var ( testInitialInterval = 5 * time.Second testRandomizationFactor = 0.1 testMultiplier = 0.5 testMaxInterval = testInitialInterval testMinInterval = 100 * time.Millisecond testMaxElapsedTime = time.Duration(0) ) exp := time_.NewExponentialBackOff( time_.WithExponentialBackOffOptionInitialInterval(testInitialInterval), time_.WithExponentialBackOffOptionRandomizationFactor(testRandomizationFactor), time_.WithExponentialBackOffOptionMultiplier(testMultiplier), time_.WithExponentialBackOffOptionMaxInterval(testMaxInterval), time_.WithExponentialBackOffOptionMinInterval(testMinInterval), time_.WithExponentialBackOffOptionMaxElapsedTime(testMaxElapsedTime), ) expectedResults := []time.Duration{500, 250, 125, 62, 31, 16, 8, 4, 2, 2, 2} for i, d := range expectedResults { expectedResults[i] = d * time.Millisecond } for _, expected := range expectedResults { // assert.Equal(t, expected, exp.GetCurrentInterval()) // Assert that the next backoff falls in the expected range. var minInterval = expected - time.Duration(testRandomizationFactor*float64(expected)) var maxInterval = expected + time.Duration(testRandomizationFactor*float64(expected)) actualInterval, over := exp.NextBackOff() t.Logf("over: %v, actualInterval: %v", over, actualInterval) if !(minInterval <= actualInterval && actualInterval <= maxInterval) { } } t.Logf("starting back...") for _, expected := range expectedResults { // assert.Equal(t, expected, exp.GetCurrentInterval()) // Assert that the next backoff falls in the expected range. var minInterval = expected - time.Duration(testRandomizationFactor*float64(expected)) var maxInterval = expected + time.Duration(testRandomizationFactor*float64(expected)) actualInterval, over := exp.PreBackOff() t.Logf("over: %v, actualInterval: %v", over, actualInterval) if !(minInterval <= actualInterval && actualInterval <= maxInterval) { } } } ================================================ FILE: go/time/exponentialbackeoff_syncmap.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time import ( "sync" // Used by sync.Map. ) type ExponentialBackOffMap sync.Map // Generate code that will fail if the constants change value. func _() { // An "cannot convert ExponentialBackOffMap literal (type ExponentialBackOffMap) to type sync.Map" compiler error signifies that the base type have changed. // Re-run the go-syncmap command to generate them again. _ = (sync.Map)(ExponentialBackOffMap{}) } var _nil_ExponentialBackOffMap_ExponentialBackOff_value = func() (val ExponentialBackOff) { return }() // Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. func (m *ExponentialBackOffMap) Load(key string) (ExponentialBackOff, bool) { value, ok := (*sync.Map)(m).Load(key) if value == nil { return _nil_ExponentialBackOffMap_ExponentialBackOff_value, ok } return value.(ExponentialBackOff), ok } // Store sets the value for a key. func (m *ExponentialBackOffMap) Store(key string, value ExponentialBackOff) { (*sync.Map)(m).Store(key, value) } // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. func (m *ExponentialBackOffMap) LoadOrStore(key string, value ExponentialBackOff) (ExponentialBackOff, bool) { actual, loaded := (*sync.Map)(m).LoadOrStore(key, value) if actual == nil { return _nil_ExponentialBackOffMap_ExponentialBackOff_value, loaded } return actual.(ExponentialBackOff), loaded } // LoadAndDelete deletes the value for a key, returning the previous value if any. // The loaded result reports whether the key was present. func (m *ExponentialBackOffMap) LoadAndDelete(key string) (value ExponentialBackOff, loaded bool) { actual, loaded := (*sync.Map)(m).LoadAndDelete(key) if actual == nil { return _nil_ExponentialBackOffMap_ExponentialBackOff_value, loaded } return actual.(ExponentialBackOff), loaded } // Delete deletes the value for a key. func (m *ExponentialBackOffMap) Delete(key string) { (*sync.Map)(m).Delete(key) } // Range calls f sequentially for each key and value present in the map. // If f returns false, range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once, but if the value for any key // is stored or deleted concurrently, Range may reflect any mapping for that key // from any point during the Range call. // // Range may be O(N) with the number of elements in the map even if f returns // false after a constant number of calls. func (m *ExponentialBackOffMap) Range(f func(key string, value ExponentialBackOff) bool) { (*sync.Map)(m).Range(func(key, value interface{}) bool { return f(key.(string), value.(ExponentialBackOff)) }) } ================================================ FILE: go/time/rate/rate.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 rate import ( "context" "fmt" "sync" "time" ) // Limiter 基于 channel 信号量的并发控制限流器 type Limiter struct { mu sync.Mutex burst int sem chan struct{} } // NewLimiter returns a new Limiter that permits bursts of at most b tokens. func NewLimiter(b int) *Limiter { if b <= 0 { b = 1 } l := &Limiter{ burst: b, sem: make(chan struct{}, b), } // 预填充令牌 for i := 0; i < b; i++ { l.sem <- struct{}{} } return l } // Burst returns the maximum burst size. func (lim *Limiter) Burst() int { lim.mu.Lock() defer lim.mu.Unlock() return lim.burst } // Tokens returns the current available tokens. func (lim *Limiter) Tokens() int { return len(lim.sem) } // Bursting returns the number of tokens currently in use. func (lim *Limiter) Bursting() int { lim.mu.Lock() defer lim.mu.Unlock() return lim.burst - len(lim.sem) } // Allow attempts to acquire a token immediately without waiting. func (lim *Limiter) Allow() bool { select { case <-lim.sem: return true default: return false } } // AllowN attempts to acquire n tokens immediately without waiting. func (lim *Limiter) AllowN(n int) bool { if n <= 0 { return true } if n > lim.burst { return false } acquired := 0 for i := 0; i < n; i++ { select { case <-lim.sem: acquired++ default: // 获取失败,归还已获取的令牌 for j := 0; j < acquired; j++ { lim.sem <- struct{}{} } return false } } return true } // AllowWaitUntil waits indefinitely until a token is available. func (lim *Limiter) AllowWaitUntil() bool { <-lim.sem return true } // AllowFor attempts to acquire a token with timeout. // If timeout < 0, it waits indefinitely. // If timeout == 0, it returns immediately. func (lim *Limiter) AllowFor(timeout time.Duration) bool { if timeout == 0 { return lim.Allow() } if timeout < 0 { return lim.AllowWaitUntil() } select { case <-lim.sem: return true case <-time.After(timeout): return false } } // AllowContext attempts to acquire a token with context support. func (lim *Limiter) AllowContext(ctx context.Context) error { select { case <-lim.sem: return nil case <-ctx.Done(): return ctx.Err() } } // Put returns one token to the limiter. func (lim *Limiter) Put() { lim.PutN(1) } // PutN returns n tokens to the limiter. func (lim *Limiter) PutN(n int) { for i := 0; i < n; i++ { select { case lim.sem <- struct{}{}: default: // channel is full, ignore } } } // WaitFor waits for one token with timeout. func (lim *Limiter) WaitFor(timeout time.Duration) error { return lim.WaitN(timeout, 1) } // WaitN waits for n tokens with timeout. func (lim *Limiter) WaitN(timeout time.Duration, n int) error { if n <= 0 { return nil } if n > lim.burst { return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst) } acquired := 0 // 失败时归还已获取的令牌 defer func() { if acquired < n { lim.PutN(acquired) } }() // 无限等待 if timeout < 0 { for acquired < n { <-lim.sem acquired++ } return nil } // 带超时等待 deadline := time.Now().Add(timeout) for acquired < n { remaining := time.Until(deadline) if remaining <= 0 { return fmt.Errorf("rate: Wait timeout after acquiring %d/%d tokens", acquired, n) } select { case <-lim.sem: acquired++ case <-time.After(remaining): return fmt.Errorf("rate: Wait timeout after acquiring %d/%d tokens", acquired, n) } } return nil } // WaitContext waits for one token with context support. func (lim *Limiter) WaitContext(ctx context.Context) error { return lim.WaitNContext(ctx, 1) } // WaitNContext waits for n tokens with context support. func (lim *Limiter) WaitNContext(ctx context.Context, n int) error { if n <= 0 { return nil } if n > lim.burst { return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst) } acquired := 0 defer func() { if acquired < n { lim.PutN(acquired) } }() for acquired < n { select { case <-lim.sem: acquired++ case <-ctx.Done(): return ctx.Err() } } return nil } // SetBurst dynamically adjusts the burst size. func (lim *Limiter) SetBurst(newBurst int) { if newBurst <= 0 { newBurst = 1 } lim.mu.Lock() defer lim.mu.Unlock() oldBurst := lim.burst if newBurst == oldBurst { return } // 创建新的 channel newSem := make(chan struct{}, newBurst) // 转移现有令牌 currentTokens := len(lim.sem) transferTokens := currentTokens if transferTokens > newBurst { transferTokens = newBurst } for i := 0; i < transferTokens; i++ { newSem <- struct{}{} } // 消耗旧 channel 中多余的令牌 for i := 0; i < currentTokens-transferTokens; i++ { <-lim.sem } lim.sem = newSem lim.burst = newBurst } ================================================ FILE: go/time/rate/rate_method.go ================================================ /* *Copyright (c) 2024, kaydxh * *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 rate import ( "fmt" "sync" "time" ) // Limiters support for differenet methods type MethodLimiter struct { mu sync.RWMutex Limiters map[string]*Limiter *Limiter } func NewMethodLimiter(burst int) *MethodLimiter { ml := &MethodLimiter{ Limiters: make(map[string]*Limiter, 0), Limiter: NewLimiter(burst), } return ml } func (m *MethodLimiter) AddLimiter(method string, limiter *Limiter) error { if method == "" { return fmt.Errorf("the method can not be empty") } if limiter == nil { return fmt.Errorf("limiter can not be nil") } m.mu.Lock() defer m.mu.Unlock() if _, ok := m.Limiters[method]; ok { return fmt.Errorf("method: %s already exist", method) } m.Limiters[method] = limiter return nil } func (m *MethodLimiter) Allow(method string) bool { m.mu.RLock() defer m.mu.RUnlock() limiter, ok := m.Limiters[method] if !ok { return m.Limiter.Allow() } return limiter.Allow() } func (m *MethodLimiter) AllowFor(method string, timeout time.Duration) bool { m.mu.RLock() defer m.mu.RUnlock() limiter, ok := m.Limiters[method] if !ok { return m.Limiter.AllowFor(timeout) } return limiter.AllowFor(timeout) } func (m *MethodLimiter) Put(method string) { m.mu.RLock() defer m.mu.RUnlock() limiter, ok := m.Limiters[method] if !ok { m.Limiter.Put() return } limiter.Put() } ================================================ FILE: go/time/rate/rate_qps.go ================================================ /* *Copyright (c) 2024, kaydxh * *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 rate import ( "context" "sync" "time" ) // QPSLimiter is a rate limiter based on token bucket algorithm. // It controls the rate of requests per second (QPS). type QPSLimiter struct { mu sync.Mutex qps float64 // tokens generated per second burst int // max tokens (bucket size) tokens float64 // current available tokens lastUpdate time.Time // last token update time } // NewQPSLimiter creates a new QPS-based rate limiter. // qps: the rate of tokens generated per second (queries per second) // burst: the maximum number of tokens that can be stored (allows burst traffic) func NewQPSLimiter(qps float64, burst int) *QPSLimiter { return &QPSLimiter{ qps: qps, burst: burst, tokens: float64(burst), lastUpdate: time.Now(), } } // SetQPS dynamically updates the QPS rate. func (l *QPSLimiter) SetQPS(qps float64) { l.mu.Lock() defer l.mu.Unlock() l.qps = qps } // SetBurst dynamically updates the burst size. func (l *QPSLimiter) SetBurst(burst int) { l.mu.Lock() defer l.mu.Unlock() l.burst = burst if l.tokens > float64(burst) { l.tokens = float64(burst) } } // QPS returns the current QPS rate. func (l *QPSLimiter) QPS() float64 { l.mu.Lock() defer l.mu.Unlock() return l.qps } // Burst returns the current burst size. func (l *QPSLimiter) Burst() int { l.mu.Lock() defer l.mu.Unlock() return l.burst } // Tokens returns the current available tokens. func (l *QPSLimiter) Tokens() float64 { l.mu.Lock() defer l.mu.Unlock() l.refillTokens() return l.tokens } // refillTokens adds tokens based on elapsed time since last update. // Must be called with lock held. func (l *QPSLimiter) refillTokens() { now := time.Now() elapsed := now.Sub(l.lastUpdate).Seconds() l.lastUpdate = now // Add tokens based on QPS and elapsed time l.tokens += elapsed * l.qps if l.tokens > float64(l.burst) { l.tokens = float64(l.burst) } } // Allow reports whether one event may happen now. // It returns true if the event is allowed, false otherwise. // This method does not block. func (l *QPSLimiter) Allow() bool { return l.AllowN(1) } // AllowN reports whether n events may happen now. // It returns true if the events are allowed, false otherwise. // This method does not block. func (l *QPSLimiter) AllowN(n int) bool { l.mu.Lock() defer l.mu.Unlock() l.refillTokens() if l.tokens >= float64(n) { l.tokens -= float64(n) return true } return false } // Wait blocks until one event is allowed or the context is canceled. func (l *QPSLimiter) Wait(ctx context.Context) error { return l.WaitN(ctx, 1) } // WaitN blocks until n events are allowed or the context is canceled. func (l *QPSLimiter) WaitN(ctx context.Context, n int) error { l.mu.Lock() l.refillTokens() if l.tokens >= float64(n) { l.tokens -= float64(n) l.mu.Unlock() return nil } // Calculate wait time tokensNeeded := float64(n) - l.tokens waitDuration := time.Duration(tokensNeeded / l.qps * float64(time.Second)) l.mu.Unlock() // Check if context has deadline and if we can wait that long if deadline, ok := ctx.Deadline(); ok { if time.Until(deadline) < waitDuration { return context.DeadlineExceeded } } timer := time.NewTimer(waitDuration) defer timer.Stop() select { case <-timer.C: l.mu.Lock() l.refillTokens() if l.tokens >= float64(n) { l.tokens -= float64(n) l.mu.Unlock() return nil } l.mu.Unlock() // Retry if not enough tokens (rare case due to timing) return l.WaitN(ctx, n) case <-ctx.Done(): return ctx.Err() } } // AllowFor tries to get a token within the specified timeout. // Returns true if a token is obtained, false if timeout expires. func (l *QPSLimiter) AllowFor(timeout time.Duration) bool { if timeout <= 0 { return l.Allow() } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() err := l.Wait(ctx) return err == nil } // Put is a no-op for QPS limiter (tokens are time-based, not returned). // This method exists to satisfy the Limiter interface compatibility. func (l *QPSLimiter) Put() { // QPS limiter uses time-based token refill, no need to return tokens } // Reserve returns a Reservation that can be used to wait for the token. func (l *QPSLimiter) Reserve() *QPSReservation { return l.ReserveN(1) } // ReserveN returns a Reservation for n tokens. func (l *QPSLimiter) ReserveN(n int) *QPSReservation { l.mu.Lock() defer l.mu.Unlock() l.refillTokens() r := &QPSReservation{ limiter: l, tokens: n, } if l.tokens >= float64(n) { l.tokens -= float64(n) r.ok = true r.timeToAct = time.Now() return r } // Calculate when we'll have enough tokens tokensNeeded := float64(n) - l.tokens waitDuration := time.Duration(tokensNeeded / l.qps * float64(time.Second)) r.ok = true r.timeToAct = time.Now().Add(waitDuration) l.tokens = 0 // Reserve all current tokens return r } // QPSReservation holds information about a rate-limited event. type QPSReservation struct { limiter *QPSLimiter ok bool tokens int timeToAct time.Time } // OK returns whether the reservation is valid. func (r *QPSReservation) OK() bool { return r.ok } // Delay returns the duration to wait before the event can happen. func (r *QPSReservation) Delay() time.Duration { delay := time.Until(r.timeToAct) if delay < 0 { return 0 } return delay } // Cancel cancels the reservation. func (r *QPSReservation) Cancel() { if !r.ok { return } r.limiter.mu.Lock() defer r.limiter.mu.Unlock() // Return tokens if we haven't acted yet if time.Now().Before(r.timeToAct) { r.limiter.tokens += float64(r.tokens) if r.limiter.tokens > float64(r.limiter.burst) { r.limiter.tokens = float64(r.limiter.burst) } } r.ok = false } ================================================ FILE: go/time/rate/rate_qps_method.go ================================================ /* *Copyright (c) 2024, kaydxh * *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 rate import ( "context" "fmt" "sync" "time" ) // MethodQPSLimiter supports different QPS limits for different API methods. type MethodQPSLimiter struct { mu sync.RWMutex limiters map[string]*QPSLimiter // method -> limiter mapping global *QPSLimiter // default global limiter } // MethodQPSConfig defines QPS configuration for a specific method. type MethodQPSConfig struct { Method string // API method name (e.g., "/api/v1/users", "/service.Method") QPS float64 // queries per second Burst int // max burst size } // NewMethodQPSLimiter creates a new method-level QPS limiter. // defaultQPS and defaultBurst are used for methods without specific configuration. func NewMethodQPSLimiter(defaultQPS float64, defaultBurst int) *MethodQPSLimiter { return &MethodQPSLimiter{ limiters: make(map[string]*QPSLimiter), global: NewQPSLimiter(defaultQPS, defaultBurst), } } // NewMethodQPSLimiterWithConfigs creates a limiter with predefined method configurations. func NewMethodQPSLimiterWithConfigs(defaultQPS float64, defaultBurst int, configs []MethodQPSConfig) (*MethodQPSLimiter, error) { m := NewMethodQPSLimiter(defaultQPS, defaultBurst) for _, cfg := range configs { if err := m.AddMethod(cfg.Method, cfg.QPS, cfg.Burst); err != nil { return nil, err } } return m, nil } // AddMethod adds a QPS limit for a specific method. func (m *MethodQPSLimiter) AddMethod(method string, qps float64, burst int) error { if method == "" { return fmt.Errorf("method cannot be empty") } if qps <= 0 { return fmt.Errorf("qps must be positive, got %v", qps) } if burst <= 0 { return fmt.Errorf("burst must be positive, got %v", burst) } m.mu.Lock() defer m.mu.Unlock() if _, exists := m.limiters[method]; exists { return fmt.Errorf("method %q already has a limiter configured", method) } m.limiters[method] = NewQPSLimiter(qps, burst) return nil } // SetMethodQPS dynamically updates the QPS for a specific method. // If the method doesn't exist, it creates a new limiter. func (m *MethodQPSLimiter) SetMethodQPS(method string, qps float64, burst int) error { if method == "" { return fmt.Errorf("method cannot be empty") } if qps <= 0 { return fmt.Errorf("qps must be positive, got %v", qps) } if burst <= 0 { return fmt.Errorf("burst must be positive, got %v", burst) } m.mu.Lock() defer m.mu.Unlock() if limiter, exists := m.limiters[method]; exists { limiter.SetQPS(qps) limiter.SetBurst(burst) } else { m.limiters[method] = NewQPSLimiter(qps, burst) } return nil } // RemoveMethod removes the QPS limit for a specific method. // After removal, the method will use the global limiter. func (m *MethodQPSLimiter) RemoveMethod(method string) { m.mu.Lock() defer m.mu.Unlock() delete(m.limiters, method) } // SetGlobalQPS updates the global (default) QPS limit. func (m *MethodQPSLimiter) SetGlobalQPS(qps float64, burst int) { m.global.SetQPS(qps) m.global.SetBurst(burst) } // getLimiter returns the limiter for the given method. // Falls back to global limiter if no specific limiter is configured. func (m *MethodQPSLimiter) getLimiter(method string) *QPSLimiter { m.mu.RLock() defer m.mu.RUnlock() if limiter, exists := m.limiters[method]; exists { return limiter } return m.global } // Allow checks if a request for the given method is allowed. // Returns true if allowed, false if rate limited. func (m *MethodQPSLimiter) Allow(method string) bool { return m.getLimiter(method).Allow() } // AllowN checks if n requests for the given method are allowed. func (m *MethodQPSLimiter) AllowN(method string, n int) bool { return m.getLimiter(method).AllowN(n) } // AllowFor tries to get permission within the specified timeout. func (m *MethodQPSLimiter) AllowFor(method string, timeout time.Duration) bool { return m.getLimiter(method).AllowFor(timeout) } // Wait blocks until a request for the given method is allowed. func (m *MethodQPSLimiter) Wait(ctx context.Context, method string) error { return m.getLimiter(method).Wait(ctx) } // WaitN blocks until n requests for the given method are allowed. func (m *MethodQPSLimiter) WaitN(ctx context.Context, method string, n int) error { return m.getLimiter(method).WaitN(ctx, n) } // Put is a no-op for QPS limiter (for interface compatibility). func (m *MethodQPSLimiter) Put(method string) { // QPS limiter uses time-based token refill, no need to return tokens } // GetMethodQPS returns the QPS configuration for a specific method. // Returns (qps, burst, exists). func (m *MethodQPSLimiter) GetMethodQPS(method string) (qps float64, burst int, exists bool) { m.mu.RLock() defer m.mu.RUnlock() if limiter, ok := m.limiters[method]; ok { return limiter.QPS(), limiter.Burst(), true } return m.global.QPS(), m.global.Burst(), false } // ListMethods returns all methods with specific QPS limits configured. func (m *MethodQPSLimiter) ListMethods() []string { m.mu.RLock() defer m.mu.RUnlock() methods := make([]string, 0, len(m.limiters)) for method := range m.limiters { methods = append(methods, method) } return methods } // Stats returns current QPS stats for all configured methods. type MethodQPSStats struct { Method string `json:"method"` QPS float64 `json:"qps"` Burst int `json:"burst"` Tokens float64 `json:"tokens"` // current available tokens } func (m *MethodQPSLimiter) Stats() []MethodQPSStats { m.mu.RLock() defer m.mu.RUnlock() stats := make([]MethodQPSStats, 0, len(m.limiters)+1) // Global limiter stats stats = append(stats, MethodQPSStats{ Method: "*", QPS: m.global.QPS(), Burst: m.global.Burst(), Tokens: m.global.Tokens(), }) // Per-method stats for method, limiter := range m.limiters { stats = append(stats, MethodQPSStats{ Method: method, QPS: limiter.QPS(), Burst: limiter.Burst(), Tokens: limiter.Tokens(), }) } return stats } ================================================ FILE: go/time/rate/rate_qps_test.go ================================================ /* *Copyright (c) 2024, kaydxh * *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 rate_test import ( "context" "sync" "sync/atomic" "testing" "time" "github.com/kaydxh/golang/go/time/rate" ) func TestQPSLimiter_Allow(t *testing.T) { // Create a limiter with 10 QPS and burst of 5 limiter := rate.NewQPSLimiter(10, 5) // Should allow burst requests immediately for i := 0; i < 5; i++ { if !limiter.Allow() { t.Errorf("Allow() should return true for burst request %d", i) } } // 6th request should be rejected (burst exhausted) if limiter.Allow() { t.Error("Allow() should return false when burst is exhausted") } // Wait for token refill (100ms = 1 token at 10 QPS) time.Sleep(110 * time.Millisecond) // Should allow one more request if !limiter.Allow() { t.Error("Allow() should return true after token refill") } } func TestQPSLimiter_Wait(t *testing.T) { limiter := rate.NewQPSLimiter(100, 1) // 100 QPS, burst 1 // Exhaust the burst limiter.Allow() // Wait with timeout ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() start := time.Now() err := limiter.Wait(ctx) elapsed := time.Since(start) if err != nil { t.Errorf("Wait() error = %v", err) } // Should wait approximately 10ms (1/100 second) if elapsed < 5*time.Millisecond || elapsed > 30*time.Millisecond { t.Errorf("Wait() took %v, expected ~10ms", elapsed) } } func TestQPSLimiter_WaitTimeout(t *testing.T) { limiter := rate.NewQPSLimiter(1, 1) // 1 QPS, burst 1 // Exhaust the burst limiter.Allow() // Wait with very short timeout (should fail) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) defer cancel() err := limiter.Wait(ctx) if err != context.DeadlineExceeded { t.Errorf("Wait() error = %v, want context.DeadlineExceeded", err) } } func TestQPSLimiter_Concurrent(t *testing.T) { limiter := rate.NewQPSLimiter(1000, 100) // 1000 QPS, burst 100 var allowed int64 var denied int64 var wg sync.WaitGroup // Launch 200 concurrent requests for i := 0; i < 200; i++ { wg.Add(1) go func() { defer wg.Done() if limiter.Allow() { atomic.AddInt64(&allowed, 1) } else { atomic.AddInt64(&denied, 1) } }() } wg.Wait() // Should allow exactly burst size immediately if allowed != 100 { t.Logf("Allowed: %d, Denied: %d (expected 100 allowed)", allowed, denied) } } func TestMethodQPSLimiter_DifferentMethods(t *testing.T) { limiter := rate.NewMethodQPSLimiter(10, 5) // Default: 10 QPS, burst 5 // Configure different QPS for different methods err := limiter.AddMethod("/api/v1/users", 100, 20) if err != nil { t.Fatalf("AddMethod() error = %v", err) } err = limiter.AddMethod("/api/v1/orders", 50, 10) if err != nil { t.Fatalf("AddMethod() error = %v", err) } // Test method-specific limits // /api/v1/users has burst of 20 for i := 0; i < 20; i++ { if !limiter.Allow("/api/v1/users") { t.Errorf("Allow() should return true for /api/v1/users request %d", i) } } if limiter.Allow("/api/v1/users") { t.Error("Allow() should return false when /api/v1/users burst is exhausted") } // /api/v1/orders has burst of 10 for i := 0; i < 10; i++ { if !limiter.Allow("/api/v1/orders") { t.Errorf("Allow() should return true for /api/v1/orders request %d", i) } } if limiter.Allow("/api/v1/orders") { t.Error("Allow() should return false when /api/v1/orders burst is exhausted") } // Unknown method uses global limiter (burst 5) for i := 0; i < 5; i++ { if !limiter.Allow("/api/v1/unknown") { t.Errorf("Allow() should return true for unknown method request %d", i) } } if limiter.Allow("/api/v1/unknown") { t.Error("Allow() should return false when global burst is exhausted") } } func TestMethodQPSLimiter_SetMethodQPS(t *testing.T) { limiter := rate.NewMethodQPSLimiter(10, 5) // Add initial config limiter.AddMethod("/api/v1/test", 100, 10) // Update QPS err := limiter.SetMethodQPS("/api/v1/test", 200, 20) if err != nil { t.Fatalf("SetMethodQPS() error = %v", err) } qps, burst, exists := limiter.GetMethodQPS("/api/v1/test") if !exists { t.Error("Method should exist") } if qps != 200 { t.Errorf("QPS = %v, want 200", qps) } if burst != 20 { t.Errorf("Burst = %v, want 20", burst) } } func TestMethodQPSLimiter_Stats(t *testing.T) { limiter := rate.NewMethodQPSLimiter(10, 5) limiter.AddMethod("/api/v1/users", 100, 20) limiter.AddMethod("/api/v1/orders", 50, 10) stats := limiter.Stats() if len(stats) != 3 { // global + 2 methods t.Errorf("Stats() returned %d entries, want 3", len(stats)) } // Check that global is included hasGlobal := false for _, s := range stats { if s.Method == "*" { hasGlobal = true if s.QPS != 10 { t.Errorf("Global QPS = %v, want 10", s.QPS) } } } if !hasGlobal { t.Error("Stats() should include global limiter") } } func TestMethodQPSLimiter_WithConfigs(t *testing.T) { configs := []rate.MethodQPSConfig{ {Method: "/api/v1/users", QPS: 100, Burst: 20}, {Method: "/api/v1/orders", QPS: 50, Burst: 10}, {Method: "/api/v1/products", QPS: 200, Burst: 50}, } limiter, err := rate.NewMethodQPSLimiterWithConfigs(10, 5, configs) if err != nil { t.Fatalf("NewMethodQPSLimiterWithConfigs() error = %v", err) } methods := limiter.ListMethods() if len(methods) != 3 { t.Errorf("ListMethods() returned %d methods, want 3", len(methods)) } // Verify each method's config for _, cfg := range configs { qps, burst, exists := limiter.GetMethodQPS(cfg.Method) if !exists { t.Errorf("Method %q should exist", cfg.Method) } if qps != cfg.QPS { t.Errorf("Method %q QPS = %v, want %v", cfg.Method, qps, cfg.QPS) } if burst != cfg.Burst { t.Errorf("Method %q Burst = %v, want %v", cfg.Method, burst, cfg.Burst) } } } func BenchmarkQPSLimiter_Allow(b *testing.B) { limiter := rate.NewQPSLimiter(1000000, 10000) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { limiter.Allow() } }) } func BenchmarkMethodQPSLimiter_Allow(b *testing.B) { limiter := rate.NewMethodQPSLimiter(1000000, 10000) limiter.AddMethod("/api/v1/users", 1000000, 10000) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { limiter.Allow("/api/v1/users") } }) } ================================================ FILE: go/time/rate/rate_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 rate_test import ( "sync" "sync/atomic" "testing" "time" rate_ "github.com/kaydxh/golang/go/time/rate" "gotest.tools/assert" ) func TestLimitAllow(t *testing.T) { // The test runs for a few seconds executing many requests and then checks // that overall number of requests is reasonable. const ( limit = 100 burst = 100 ) var ( numAll int32 = 0 numOK int32 = 0 numFailed int32 = 0 ) lim := rate_.NewLimiter(burst) var wg sync.WaitGroup f := func() { if ok := lim.Allow(); ok { defer lim.Put() atomic.AddInt32(&numOK, 1) time.Sleep(10 * time.Millisecond) } else { atomic.AddInt32(&numFailed, 1) // t.Logf("not Allowed, bursting: %v", lim.Bursting()) } atomic.AddInt32(&numAll, 1) wg.Done() } start := time.Now() end := start.Add(5 * time.Second) for time.Now().Before(end) { wg.Add(1) go f() } wg.Wait() assert.Equal(t, numAll, numOK+numFailed) // numOK should get very close to the number of requests allowed 50000. t.Logf("%v request ==> %v requset Allowed, %v request Unallowed ", numAll, numOK, numFailed) } func TestLimitAllowFor(t *testing.T) { // The test runs for a few seconds executing many requests and then checks // that overall number of requests is reasonable. const ( limit = 100 burst = 100 ) var ( numAll int32 = 0 numOK int32 = 0 numFailed int32 = 0 ) //timout > 5s, so must process 50001 times timeout := 6 * time.Second lim := rate_.NewLimiter(burst) var wg sync.WaitGroup f := func() { if ok := lim.AllowFor(timeout); ok { defer lim.Put() atomic.AddInt32(&numOK, 1) //about process 50000 times in 5s time.Sleep(10 * time.Millisecond) } else { atomic.AddInt32(&numFailed, 1) // t.Logf("not Allowed, bursting: %v", lim.Bursting()) } atomic.AddInt32(&numAll, 1) wg.Done() } for i := 0; i < 50001; i++ { wg.Add(1) go f() } wg.Wait() assert.Equal(t, numAll, numOK+numFailed) // numOK should get very close to the number of requests allowed 50000. t.Logf("%v request ==> %v requset Allowed, %v request Unallowed ", numAll, numOK, numFailed) } ================================================ FILE: go/time/time.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time import "time" const ( DayFormat = "20060102" TimeMillFormat = "20060102150405.000" ShortTimeFormat = "20060102150405" ShortDashTimeFormat = "2006-01-02-15:04:05" DefaultTimeFormat = "2006-01-02 15:04:05" DefaultTimeMillFormat = "2006-01-02 15:04:05.000" ) func Now() time.Time { now := time.Now() return now } func NowString(layout string) string { tm := Now() if layout == "" { layout = DefaultTimeFormat } return tm.Format(layout) } func BeginningOfDay(days int) time.Time { now := time.Now() theDay := now.AddDate(0, 0, days) y, m, d := theDay.Date() return time.Date(y, m, d, 0, 0, 0, 0, theDay.Location()) } func BeginningOfDayString(days int, layout string) string { now := time.Now() theDay := now.AddDate(0, 0, days) y, m, d := theDay.Date() if layout == "" { layout = DefaultTimeFormat } return time.Date(y, m, d, 0, 0, 0, 0, theDay.Location()).Format(layout) } func EndOfDay(days int) time.Time { now := time.Now() theDay := now.AddDate(0, 0, days) y, m, d := theDay.Date() return time.Date(y, m, d, 23, 59, 59, int(time.Second-time.Nanosecond), theDay.Location()) } func EndOfDayString(days int, layout string) string { now := time.Now() theDay := now.AddDate(0, 0, days) y, m, d := theDay.Date() if layout == "" { layout = DefaultTimeFormat } return time.Date( y, m, d, 23, 59, 59, int(time.Second-time.Nanosecond), theDay.Location(), ).Format(layout) } // Truncate only happens in UTC semantics, apparently. // observed values for truncating given time with 86400 secs: // // before truncation: 2018/06/01 03:54:54 2018-06-01T03:18:00+09:00 // after truncation: 2018/06/01 03:54:54 2018-05-31T09:00:00+09:00 // // This is really annoying when we want to truncate in local time // so we hack: we take the apparent local time in the local zone, // and pretend that it's in UTC. do our math, and put it back to // the local zone func TruncateToUTC(t time.Time, d time.Duration) time.Time { if t.Location() == time.UTC { return t.Truncate(d) } base := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) base = base.Truncate(d) return time.Date( base.Year(), base.Month(), base.Day(), base.Hour(), base.Minute(), base.Second(), base.Nanosecond(), base.Location(), ) } func TruncateToUTCString(t time.Time, d time.Duration, layout string) string { utc := TruncateToUTC(t, d) if layout == "" { layout = DefaultTimeFormat } return utc.Format(layout) } ================================================ FILE: go/time/time_counter.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time import ( "fmt" "strings" "time" ) type TimeCounter struct { starts []time.Time message []string effect bool } func New(effect bool) *TimeCounter { t := &TimeCounter{ effect: effect, } if effect { t.starts = append(t.starts, time.Now()) t.message = append(t.message, "start") } return t } func (t *TimeCounter) Tick(msg string) { if t.effect { t.starts = append(t.starts, time.Now()) t.message = append(t.message, msg) } } func (t *TimeCounter) Elapse() time.Duration { if !t.effect { return time.Duration(0) } if len(t.starts) == 0 { return time.Duration(0) } return time.Now().Sub(t.starts[0]) } func (t *TimeCounter) String() string { if !t.effect { return "" } var buf strings.Builder t.Summary(func(idx int, msg string, cost time.Duration, at time.Time) { buf.WriteString(fmt.Sprintf("#%d, msg: %s, cost: %s, at %s ", idx, msg, cost, at.Format(time.RFC3339))) }) return buf.String() } func (t *TimeCounter) Summary(f func(idx int, msg string, cost time.Duration, at time.Time)) { if !t.effect { return } if f == nil || t == nil { return } if len(t.message) < len(t.starts) { return } for i := 1; i < len(t.starts); i++ { f(i, t.message[i], t.starts[i].Sub(t.starts[i-1]), t.starts[i]) } } func (t *TimeCounter) Reset() { t.starts = nil t.message = nil } ================================================ FILE: go/time/time_counter_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time_test import ( "fmt" "testing" "time" time_ "github.com/kaydxh/golang/go/time" ) func TestAll(t *testing.T) { //var tc time_.TimeCounter tc := time_.New(true) func(module string) { time.Sleep(time.Second) }("module1") tc.Tick("module1") func(module string) { time.Sleep(time.Second * 4) }("module2") tc.Tick("module2") fmt.Println(tc.String()) } ================================================ FILE: go/time/time_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time_test import ( "testing" "time" time_ "github.com/kaydxh/golang/go/time" ) func TestNowString(t *testing.T) { now := time_.NowString("") t.Logf("now: %s", now) } func TestBeginningOfDayString(t *testing.T) { beginTime := time_.BeginningOfDayString(-1, "") t.Logf("beginTime: %s", beginTime) } func TestEndOfDayString(t *testing.T) { endTime := time_.EndOfDayString(-1, "") t.Logf("endTime: %s", endTime) } func TestTruncateToUTCString(t *testing.T) { now := time.Now() tms := time_.TruncateToUTCString(now, time.Millisecond, time_.DefaultTimeMillFormat) tsc := time_.TruncateToUTCString(now, time.Second, time_.DefaultTimeMillFormat) tmt := time_.TruncateToUTCString(now, time.Minute, time_.DefaultTimeMillFormat) thr := time_.TruncateToUTCString(now, time.Hour, time_.DefaultTimeMillFormat) t.Logf("TruncateToUTC Millisecond: %v, Second: %v, Minute: %v, Hour: %v", tms, tsc, tmt, thr) } func TestNowFormat(t *testing.T) { now := time.Now() tm := now.Format(time_.ShortDashTimeFormat) t.Logf("Now: %v", tm) } ================================================ FILE: go/time/wait.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time import ( "context" "errors" "fmt" "time" errors_ "github.com/kaydxh/golang/go/errors" runtime_ "github.com/kaydxh/golang/go/runtime" "github.com/sirupsen/logrus" ) var ErrTimeout = errors.New("timeout error") // Until loops until context timout, running f every period. // Until is syntactic sugar on top of JitterUntil with zero jitter factor and // with sliding = true (which means the timer for period starts after the f // completes). func UntilWithContxt( ctx context.Context, f func(ctx context.Context) error, period time.Duration) { JitterUntilWithContext(ctx, f, period) } func JitterUntilWithContext( ctx context.Context, f func(ctx context.Context) error, period time.Duration, ) { BackOffUntilWithContext(ctx, f, NewExponentialBackOff( // forever run WithExponentialBackOffOptionMaxElapsedTime(0), WithExponentialBackOffOptionInitialInterval(period), // ensure equal interval WithExponentialBackOffOptionMultiplier(1), WithExponentialBackOffOptionRandomizationFactor(0), ), true, true) } // RetryWithContext retryTime is not include the first call func RetryWithContext( ctx context.Context, f func(ctx context.Context) error, period time.Duration, retryTimes int, ) error { return BackOffUntilWithContext(ctx, f, NewExponentialBackOff( // forever run WithExponentialBackOffOptionMaxElapsedTime(0), WithExponentialBackOffOptionInitialInterval(period), WithExponentialBackOffOptionRandomizationFactor(0), WithExponentialBackOffOptionMaxElapsedCount(retryTimes), ), true, false) } // loop true -> BackOffUntilWithContext return until time expired // loop false -> BackOffUntilWithContext return if f return nil, or time expired func BackOffUntilWithContext( ctx context.Context, f func(ctx context.Context) error, backoff Backoff, sliding bool, loop bool, ) (err error) { var ( t time.Duration remain time.Duration expired bool ) for { select { case <-ctx.Done(): return fmt.Errorf("context cancelled: %v", ctx.Err()) default: } tc := New(true) if !sliding { // If it is false then period includes the runtime for f t, expired = backoff.NextBackOff() } func() { defer runtime_.Recover() err = f(ctx) logrus.Infof("finish call function, err[%v]", err) }() if !loop { if err == nil { return nil } } if sliding { // If sliding is true, the period is computed after f runs tc.Reset() t, expired = backoff.NextBackOff() } if !expired { return errors_.Errore( fmt.Errorf("got max wait time or max count"), err) } remain = t - tc.Elapse() // fmt.Printf("remain: %v, data: %v\n", remain, time.Now().String()) func() { if remain <= 0 { return } timer := time.NewTimer(remain) defer timer.Stop() // NOTE: b/c there is no priority selection in golang // it is possible for this to race, meaning we could // trigger t.C and stopCh, and t.C select falls through. // In order to mitigate we re-check stopCh at the beginning // of every loop to prevent extra executions of f(). select { case <-ctx.Done(): return case <-timer.C: } }() } } func CallWithTimeout(ctx context.Context, timeout time.Duration, f func(ctx context.Context) error) error { tc := New(true) // never timeout if timeout <= 0 { err := f(ctx) tc.Tick("call func") logrus.WithField("module", "CallWithTimeout"). WithField("timeout", timeout). Infof("finish call function %v, err: %v", tc.String(), err) return err } // 创建带超时的 context timeoutCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() // 确保取消,避免资源泄漏 // 使用 channel 传递结果(避免数据竞争) type result struct { err error } done := make(chan result, 1) go func() { err := f(timeoutCtx) // 使用带超时的 context tc.Tick("call func") // 非阻塞发送结果,避免 goroutine 泄漏 select { case done <- result{err: err}: logrus.WithField("module", "CallWithTimeout"). WithField("timeout", timeout). Infof("finish call function %v, err: %v", tc.String(), err) case <-timeoutCtx.Done(): // 超时了,不发送结果 logrus.WithField("module", "CallWithTimeout"). Warnf("function completed after timeout, err: %v", err) } }() select { case <-ctx.Done(): return ctx.Err() case res := <-done: return res.err case <-timeoutCtx.Done(): return ErrTimeout } } ================================================ FILE: go/time/wait_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 time_test import ( "context" "fmt" "testing" "time" time_ "github.com/kaydxh/golang/go/time" ) func TestBackOffUntilWithContext(t *testing.T) { testCases := []struct { name string period time.Duration sliding bool f func(context.Context) error loop bool }{ { name: "test-sliding", period: 5 * time.Second, sliding: true, f: func(context.Context) error { time.Sleep(time.Second) fmt.Println("test-sliding") return nil }, loop: true, }, { name: "test-nonsliding", sliding: false, period: 5 * time.Second, f: func(context.Context) error { time.Sleep(time.Second) fmt.Println("test-nonsliding") return nil }, loop: true, }, { name: "test-nonsliding", sliding: false, period: 5 * time.Second, f: func(context.Context) error { time.Sleep(time.Second) fmt.Println("test-nonsliding") return nil }, loop: false, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { //ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) //defer cancel() ctx := context.Background() time_.BackOffUntilWithContext( ctx, testCase.f, time_.NewExponentialBackOff( // forever run //time_.WithExponentialBackOffOptionMaxElapsedTime(0), time_.WithExponentialBackOffOptionMaxElapsedTime(20*time.Second), time_.WithExponentialBackOffOptionInitialInterval(testCase.period), time_.WithExponentialBackOffOptionMultiplier(1), time_.WithExponentialBackOffOptionRandomizationFactor(0), ), testCase.sliding, true, ) /* if err != nil { t.Fatalf("failed to write file: %v, got : %s", testCase.name, err) } */ }) } } func TestRetryWithContext(t *testing.T) { testCases := []struct { name string period time.Duration retryTime int f func(context.Context) error }{ { name: "test-retry-nil", period: 5 * time.Second, retryTime: 3, f: func(context.Context) error { time.Sleep(time.Second) fmt.Println("test-sliding") return nil }, }, { name: "test-retry-error", period: 5 * time.Second, retryTime: 5, f: func(context.Context) error { time.Sleep(time.Second) fmt.Println("test-retry-error-sliding") return fmt.Errorf("error") }, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { //ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) //defer cancel() ctx := context.Background() err := time_.RetryWithContext( ctx, testCase.f, testCase.period, testCase.retryTime, ) if err != nil { t.Fatalf("failed to call RetryWithContext: %v, got : %s", testCase.name, err) } }) } } ================================================ FILE: go/unsafe/unsafe.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 unsafe import "unsafe" func BytesPointer(data []byte) unsafe.Pointer { if len(data) == 0 { return nil } return unsafe.Pointer(&data[0]) } ================================================ FILE: go/utils/compare.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 utils import ( "fmt" "reflect" ) type Comparable interface { Equals(a, b interface{}) bool } type Comparator interface { Compare(a, b interface{}) int } func CheckComparableTypes(objs ...interface{}) bool { for _, obj := range objs { if !CheckComparableType(obj) { return false } } return true } func CheckComparableType(a interface{}) bool { switch reflect.ValueOf(a).Kind() { case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map: return false default: return true } } // object (a or b) that contains members that has equality defined will // have equality defined or die. func Equal(a, b interface{}) (bool, error) { if !CheckComparableTypes(a, b) { _, ok := a.(Comparable) if !ok { return false, fmt.Errorf("not support compare type: %v", reflect.ValueOf(a).Kind()) } _, ok = b.(Comparable) if !ok { return false, fmt.Errorf("not support compare type: %v", reflect.ValueOf(a).Kind()) } } if a == nil || b == nil { return a == b, nil } v1 := reflect.ValueOf(a) v2 := reflect.ValueOf(b) if v1.Type() != v2.Type() { return false, nil } return a == b, nil } func DeepEqual(a, b interface{}) bool { return reflect.DeepEqual(a, b) } func Compare(a, b interface{}, compare Comparator) int { return compare.Compare(a, b) } ================================================ FILE: go/utils/generics_get.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 utils func GetValueOrFallback[T comparable] (v, defaultValue T) T { var t T if v == t { return defaultValue } return v } func Pointer[T any](v T) *T { return &v } ================================================ FILE: go/utils/generics_get_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 utils_test import ( "testing" utils_ "github.com/kaydxh/golang/go/utils" ) func TestGetValueOrFallback(t *testing.T) { result := utils_.GetValueOrFallback(0, 20) t.Logf("result: %v", result) } ================================================ FILE: go.mod ================================================ module github.com/kaydxh/golang go 1.24.0 require ( github.com/go-playground/validator/v10 v10.28.0 github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/stretchr/testify v1.11.1 ) require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) replace github.com/kaydxh/golang/go => ./go ================================================ FILE: go.sum ================================================ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: pkg/binlog/binlog.archive.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 binlog import ( "context" "encoding/json" queue_ "github.com/kaydxh/golang/pkg/pool/taskqueue/queue" io_ "github.com/kaydxh/golang/go/io" s3_ "github.com/kaydxh/golang/pkg/storage/s3" "github.com/sirupsen/logrus" ) const ( ArchiveTaskScheme = "ArchiveTaskTask" ) type ArchiveTaskArgs struct { LocalFilePath string RemoteRootPath string } type ArchiveTask struct { bucket *s3_.Storage } func (t ArchiveTask) Scheme() string { return ArchiveTaskScheme } func (t ArchiveTask) TaskHandler(ctx context.Context, msg *queue_.Message) (*queue_.MessageResult, error) { logger := logrus.WithField("message_id", msg.Id). WithField("message_inner_id", msg.InnerId). WithField("module", "TaskHandler") result := &queue_.MessageResult{ Id: msg.Id, InnerId: msg.InnerId, Name: msg.Name, Scheme: msg.Scheme, } var args ArchiveTaskArgs err := json.Unmarshal([]byte(msg.Args), &args) if err != nil { logger.WithError(err).Errorf("failed to unmarshal msg: %v", msg) return result, err } data, err := io_.ReadFile(args.LocalFilePath) if err != nil { logger.WithError(err).Errorf("failed to read binlog[%v]", args.LocalFilePath) return result, err } if len(data) == 0 { logger.Infof("binlog[%v] is empty, not need to archive", args.LocalFilePath) return result, nil } s3Path := args.RemoteRootPath err = t.bucket.WriteAll(ctx, s3Path, data, nil) if err != nil { logger.WithError(err).Errorf("failed to upload data size[%v] to s3[%v]", len(data), s3Path) return result, err } return result, nil } ================================================ FILE: pkg/binlog/binlog.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 binlog import ( "context" "encoding/json" "fmt" "os" "path/filepath" "sync" "sync/atomic" "time" "github.com/google/uuid" "github.com/kaydxh/golang/go/errors" ds_ "github.com/kaydxh/golang/pkg/binlog/datastore" mq_ "github.com/kaydxh/golang/pkg/mq" taskq_ "github.com/kaydxh/golang/pkg/pool/taskqueue" queue_ "github.com/kaydxh/golang/pkg/pool/taskqueue/queue" "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" ) type MessageDecoderFunc func(ctx context.Context, data []byte) (interface{}, error) type MessageKeyDecodeFunc func(ctx context.Context, data []byte) (ds_.MessageKey, error) type BinlogOptions struct { rootPath string prefixName string suffixName string flushBatchSize int flushInterval time.Duration rotateInterval time.Duration rotateSize int64 remotePrefixPath string archive bool msgDecodeFunc MessageDecoderFunc msgKeyDecodeFunc MessageKeyDecodeFunc } type Channel struct { Name string } type BinlogService struct { consumers []mq_.Consumer dataStore ds_.DataStore taskq *taskq_.Pool opts BinlogOptions inShutdown atomic.Bool mu sync.Mutex cancel func() } func defaultBinlogServiceOptions() BinlogOptions { opts := BinlogOptions{ prefixName: "segment", suffixName: "log", flushBatchSize: 1024, //flushBatchSize: 5, flushInterval: time.Second, // 1s rotateInterval: time.Hour, rotateSize: 100 * 1024 * 1024, //100M } path, err := os.Getwd() if err != nil { path = "/" } opts.rootPath = path return opts } func NewBinlogService(dataStore ds_.DataStore, taskq *taskq_.Pool, consumers []mq_.Consumer, opts ...BinlogServiceOption) (*BinlogService, error) { /* if taskq == nil { return nil, fmt.Errorf("taskq is empty") } */ if len(consumers) == 0 { return nil, fmt.Errorf("consumers is empty") } bs := &BinlogService{ dataStore: dataStore, taskq: taskq, consumers: consumers, opts: defaultBinlogServiceOptions(), } bs.ApplyOptions(opts...) return bs, nil } // send archive path to topic func (srv *BinlogService) rotateCallback(ctx context.Context, path string) { logger := srv.logger() if srv.taskq == nil { return } if srv.opts.archive { args := &ArchiveTaskArgs{ LocalFilePath: path, RemoteRootPath: filepath.Join(srv.opts.remotePrefixPath, filepath.Base(path)), } data, err := json.Marshal(args) if err != nil { logger.WithError(err).Errorf("failed to marshal args: %v", args) return } id := uuid.NewString() msg := &queue_.Message{ Id: id, Name: id, Scheme: ArchiveTaskScheme, Args: string(data), } _, err = srv.taskq.Publish(ctx, msg) if err != nil { logger.WithError(err).Errorf("failed to publish msg: %v", msg) return } } } func (srv *BinlogService) logger() logrus.FieldLogger { return logrus.WithField("module", "BinlogService") } func (srv *BinlogService) Run(ctx context.Context) error { logger := srv.logger() logger.Infoln("BinlogService Run") if srv.inShutdown.Load() { logger.Infoln("BinlogService Shutdown") return fmt.Errorf("server closed") } go func() { errors.HandleError(srv.Serve(ctx)) }() return nil } func (srv *BinlogService) work(ctx context.Context, msgCh <-chan *ds_.Message) { logger := srv.logger() timer := time.NewTimer(srv.opts.flushInterval) defer timer.Stop() var ( flushBatchData []interface{} lastMsgKey ds_.MessageKey ) operateFunc := func() { for { select { case <-ctx.Done(): return case <-timer.C: logger.Info("start to flush timer") if len(flushBatchData) > 0 { _, err := srv.dataStore.WriteData(ctx, flushBatchData, lastMsgKey) if err != nil { } flushBatchData = nil logger.Info("finished to flush timer") } timer.Reset(srv.opts.flushInterval) case msg, ok := <-msgCh: if !ok { return } var msgValue interface{} var err error if srv.opts.msgDecodeFunc != nil { msgValue, err = srv.opts.msgDecodeFunc(ctx, msg.Value) if err != nil { break } } else { msgValue = msg.Value } msgKey := ds_.MessageKey{ Key: string(msg.Key), } if srv.opts.msgKeyDecodeFunc != nil { msgKey, err = srv.opts.msgKeyDecodeFunc(ctx, msg.Key) if err != nil { break } } if msgKey.MsgType != ds_.MsgType_Insert { if len(flushBatchData) > 0 { _, err = srv.dataStore.WriteData(ctx, flushBatchData, lastMsgKey) flushBatchData = nil } //todo do the msg continue } else { // insert type if len(flushBatchData) == 0 || msgKey.Equual(lastMsgKey) { flushBatchData = append(flushBatchData, msgValue) lastMsgKey = msgKey } else { logger.Infof("current msg key[%v] is not equal last msg key[%v]", msgKey, lastMsgKey) if len(flushBatchData) > 0 { _, err = srv.dataStore.WriteData(ctx, flushBatchData, lastMsgKey) flushBatchData = nil } //todo do the msg continue } } if len(flushBatchData) >= srv.opts.flushBatchSize { logger.Infof("flush batch data size[%v] >= flush batch size[%v]", len(flushBatchData), srv.opts.flushBatchSize) _, err = srv.dataStore.WriteData(ctx, flushBatchData[:srv.opts.flushBatchSize], lastMsgKey) flushBatchData = flushBatchData[srv.opts.flushBatchSize:] if err != nil { break } // https://github.com/golang/go/issues/27169 // https://tonybai.com/2016/12/21/how-to-use-timer-reset-in-golang-correctly/ if !timer.Stop() { select { case <-timer.C: default: } } timer.Reset(srv.opts.flushInterval) } } } } go operateFunc() return } func (srv *BinlogService) flush(ctx context.Context, consumer mq_.Consumer) error { logger := srv.logger() msgCh := make(chan *ds_.Message) srv.work(ctx, msgCh) for msg := range consumer.ReadStream(ctx) { logger.Infof("recv message key[%v] value[%v] from channel[%v]", string(msg.Key()), string(msg.Value()), consumer.Topic()) if msg.Error() != nil { logger.WithError(msg.Error()).Errorf("faild to read stream %v", consumer.Topic()) continue } msgWrap := &ds_.Message{ Key: msg.Key(), Value: msg.Value(), } msgCh <- msgWrap } return nil } func (srv *BinlogService) Serve(ctx context.Context) error { logger := srv.logger() logger.Infoln("ServiceBinlog Serve") if srv.inShutdown.Load() { err := fmt.Errorf("server closed") logger.WithError(err).Errorf("ServiceBinlog Serve canceled") return err } defer srv.inShutdown.Store(true) ctx, cancel := context.WithCancel(ctx) srv.mu.Lock() srv.cancel = cancel srv.mu.Unlock() g, gCtx := errgroup.WithContext(ctx) for _, consumer := range srv.consumers { consumer := consumer g.Go(func() error { return srv.flush(gCtx, consumer) }) } err := g.Wait() if err != nil { logger.WithError(err).Errorf("wait flush worker") return err } logger.Info("stopped binlog service") return nil } func (srv *BinlogService) Shutdown() { srv.inShutdown.Store(true) srv.mu.Lock() defer srv.mu.Unlock() for _, consumer := range srv.consumers { if consumer != nil { consumer.Close() } } if srv.cancel != nil { srv.cancel() } } ================================================ FILE: pkg/binlog/binlog.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 binlog import "time" func WitRootPath(rootPath string) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.rootPath = rootPath }) } func WithPrefixName(prefixName string) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.prefixName = prefixName }) } func WithSufffixName(suffixName string) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.suffixName = suffixName }) } func WithFlushBatchSize(batch int) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.flushBatchSize = batch }) } func WithFlushInterval(flushInterval time.Duration) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.flushInterval = flushInterval }) } func WithRotateInterval(rotateInterval time.Duration) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.rotateInterval = rotateInterval }) } func WithRotateSize(rotateSize int64) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.rotateSize = rotateSize }) } func WithMessageDecoderFunc(f MessageDecoderFunc) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.msgDecodeFunc = f }) } func WithMessageKeyDecodeFunc(f MessageKeyDecodeFunc) BinlogServiceOption { return BinlogServiceOptionFunc(func(c *BinlogService) { c.opts.msgKeyDecodeFunc = f }) } ================================================ FILE: pkg/binlog/binlog.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.13.0 // source: pkg/binlog/binlog.proto package binlog import ( duration "github.com/golang/protobuf/ptypes/duration" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type BinlogType int32 const ( BinlogType_BinlogType_DB BinlogType = 0 BinlogType_BinlogType_File BinlogType = 1 ) // Enum value maps for BinlogType. var ( BinlogType_name = map[int32]string{ 0: "BinlogType_DB", 1: "BinlogType_File", } BinlogType_value = map[string]int32{ "BinlogType_DB": 0, "BinlogType_File": 1, } ) func (x BinlogType) Enum() *BinlogType { p := new(BinlogType) *p = x return p } func (x BinlogType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (BinlogType) Descriptor() protoreflect.EnumDescriptor { return file_pkg_binlog_binlog_proto_enumTypes[0].Descriptor() } func (BinlogType) Type() protoreflect.EnumType { return &file_pkg_binlog_binlog_proto_enumTypes[0] } func (x BinlogType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use BinlogType.Descriptor instead. func (BinlogType) EnumDescriptor() ([]byte, []int) { return file_pkg_binlog_binlog_proto_rawDescGZIP(), []int{0} } type Binlog struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` BinlogType BinlogType `protobuf:"varint,2,opt,name=binlog_type,json=binlogType,proto3,enum=go.pkg.binlog.BinlogType" json:"binlog_type,omitempty"` FlushBatchSize int64 `protobuf:"varint,3,opt,name=flush_batch_size,json=flushBatchSize,proto3" json:"flush_batch_size,omitempty"` MaxFlushInterval *duration.Duration `protobuf:"bytes,4,opt,name=max_flush_interval,json=maxFlushInterval,proto3" json:"max_flush_interval,omitempty"` FlushTimeout *duration.Duration `protobuf:"bytes,5,opt,name=flush_timeout,json=flushTimeout,proto3" json:"flush_timeout,omitempty"` DbLog *Binlog_DBLog `protobuf:"bytes,20,opt,name=db_log,json=dbLog,proto3" json:"db_log,omitempty"` FileLog *Binlog_FileLog `protobuf:"bytes,21,opt,name=file_log,json=fileLog,proto3" json:"file_log,omitempty"` } func (x *Binlog) Reset() { *x = Binlog{} if protoimpl.UnsafeEnabled { mi := &file_pkg_binlog_binlog_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Binlog) String() string { return protoimpl.X.MessageStringOf(x) } func (*Binlog) ProtoMessage() {} func (x *Binlog) ProtoReflect() protoreflect.Message { mi := &file_pkg_binlog_binlog_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Binlog.ProtoReflect.Descriptor instead. func (*Binlog) Descriptor() ([]byte, []int) { return file_pkg_binlog_binlog_proto_rawDescGZIP(), []int{0} } func (x *Binlog) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *Binlog) GetBinlogType() BinlogType { if x != nil { return x.BinlogType } return BinlogType_BinlogType_DB } func (x *Binlog) GetFlushBatchSize() int64 { if x != nil { return x.FlushBatchSize } return 0 } func (x *Binlog) GetMaxFlushInterval() *duration.Duration { if x != nil { return x.MaxFlushInterval } return nil } func (x *Binlog) GetFlushTimeout() *duration.Duration { if x != nil { return x.FlushTimeout } return nil } func (x *Binlog) GetDbLog() *Binlog_DBLog { if x != nil { return x.DbLog } return nil } func (x *Binlog) GetFileLog() *Binlog_FileLog { if x != nil { return x.FileLog } return nil } type Binlog_DBLog struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *Binlog_DBLog) Reset() { *x = Binlog_DBLog{} if protoimpl.UnsafeEnabled { mi := &file_pkg_binlog_binlog_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Binlog_DBLog) String() string { return protoimpl.X.MessageStringOf(x) } func (*Binlog_DBLog) ProtoMessage() {} func (x *Binlog_DBLog) ProtoReflect() protoreflect.Message { mi := &file_pkg_binlog_binlog_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Binlog_DBLog.ProtoReflect.Descriptor instead. func (*Binlog_DBLog) Descriptor() ([]byte, []int) { return file_pkg_binlog_binlog_proto_rawDescGZIP(), []int{0, 0} } type Binlog_FileLog struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Filepath string `protobuf:"bytes,3,opt,name=filepath,proto3" json:"filepath,omitempty"` MaxAge *duration.Duration `protobuf:"bytes,4,opt,name=max_age,json=maxAge,proto3" json:"max_age,omitempty"` MaxCount int64 `protobuf:"varint,5,opt,name=max_count,json=maxCount,proto3" json:"max_count,omitempty"` RotateInterval *duration.Duration `protobuf:"bytes,6,opt,name=rotate_interval,json=rotateInterval,proto3" json:"rotate_interval,omitempty"` RotateSize int64 `protobuf:"varint,7,opt,name=rotate_size,json=rotateSize,proto3" json:"rotate_size,omitempty"` } func (x *Binlog_FileLog) Reset() { *x = Binlog_FileLog{} if protoimpl.UnsafeEnabled { mi := &file_pkg_binlog_binlog_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Binlog_FileLog) String() string { return protoimpl.X.MessageStringOf(x) } func (*Binlog_FileLog) ProtoMessage() {} func (x *Binlog_FileLog) ProtoReflect() protoreflect.Message { mi := &file_pkg_binlog_binlog_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Binlog_FileLog.ProtoReflect.Descriptor instead. func (*Binlog_FileLog) Descriptor() ([]byte, []int) { return file_pkg_binlog_binlog_proto_rawDescGZIP(), []int{0, 1} } func (x *Binlog_FileLog) GetFilepath() string { if x != nil { return x.Filepath } return "" } func (x *Binlog_FileLog) GetMaxAge() *duration.Duration { if x != nil { return x.MaxAge } return nil } func (x *Binlog_FileLog) GetMaxCount() int64 { if x != nil { return x.MaxCount } return 0 } func (x *Binlog_FileLog) GetRotateInterval() *duration.Duration { if x != nil { return x.RotateInterval } return nil } func (x *Binlog_FileLog) GetRotateSize() int64 { if x != nil { return x.RotateSize } return 0 } var File_pkg_binlog_binlog_proto protoreflect.FileDescriptor var file_pkg_binlog_binlog_proto_rawDesc = []byte{ 0x0a, 0x17, 0x70, 0x6b, 0x67, 0x2f, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x2f, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xe6, 0x04, 0x0a, 0x06, 0x42, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x3a, 0x0a, 0x0b, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x2e, 0x42, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x54, 0x79, 0x70, 0x65, 0x12, 0x28, 0x0a, 0x10, 0x66, 0x6c, 0x75, 0x73, 0x68, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x66, 0x6c, 0x75, 0x73, 0x68, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x47, 0x0a, 0x12, 0x6d, 0x61, 0x78, 0x5f, 0x66, 0x6c, 0x75, 0x73, 0x68, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x10, 0x6d, 0x61, 0x78, 0x46, 0x6c, 0x75, 0x73, 0x68, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x3e, 0x0a, 0x0d, 0x66, 0x6c, 0x75, 0x73, 0x68, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x66, 0x6c, 0x75, 0x73, 0x68, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x32, 0x0a, 0x06, 0x64, 0x62, 0x5f, 0x6c, 0x6f, 0x67, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x2e, 0x42, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x2e, 0x44, 0x42, 0x4c, 0x6f, 0x67, 0x52, 0x05, 0x64, 0x62, 0x4c, 0x6f, 0x67, 0x12, 0x38, 0x0a, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x6c, 0x6f, 0x67, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x2e, 0x42, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x4c, 0x6f, 0x67, 0x52, 0x07, 0x66, 0x69, 0x6c, 0x65, 0x4c, 0x6f, 0x67, 0x1a, 0x07, 0x0a, 0x05, 0x44, 0x42, 0x4c, 0x6f, 0x67, 0x1a, 0xdb, 0x01, 0x0a, 0x07, 0x46, 0x69, 0x6c, 0x65, 0x4c, 0x6f, 0x67, 0x12, 0x1a, 0x0a, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x70, 0x61, 0x74, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x70, 0x61, 0x74, 0x68, 0x12, 0x32, 0x0a, 0x07, 0x6d, 0x61, 0x78, 0x5f, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x06, 0x6d, 0x61, 0x78, 0x41, 0x67, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x42, 0x0a, 0x0f, 0x72, 0x6f, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0e, 0x72, 0x6f, 0x74, 0x61, 0x74, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x1f, 0x0a, 0x0b, 0x72, 0x6f, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x72, 0x6f, 0x74, 0x61, 0x74, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x2a, 0x34, 0x0a, 0x0a, 0x42, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x54, 0x79, 0x70, 0x65, 0x12, 0x11, 0x0a, 0x0d, 0x42, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x54, 0x79, 0x70, 0x65, 0x5f, 0x44, 0x42, 0x10, 0x00, 0x12, 0x13, 0x0a, 0x0f, 0x42, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x54, 0x79, 0x70, 0x65, 0x5f, 0x46, 0x69, 0x6c, 0x65, 0x10, 0x01, 0x42, 0x28, 0x5a, 0x26, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x3b, 0x62, 0x69, 0x6e, 0x6c, 0x6f, 0x67, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_pkg_binlog_binlog_proto_rawDescOnce sync.Once file_pkg_binlog_binlog_proto_rawDescData = file_pkg_binlog_binlog_proto_rawDesc ) func file_pkg_binlog_binlog_proto_rawDescGZIP() []byte { file_pkg_binlog_binlog_proto_rawDescOnce.Do(func() { file_pkg_binlog_binlog_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_binlog_binlog_proto_rawDescData) }) return file_pkg_binlog_binlog_proto_rawDescData } var file_pkg_binlog_binlog_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_pkg_binlog_binlog_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_pkg_binlog_binlog_proto_goTypes = []interface{}{ (BinlogType)(0), // 0: go.pkg.binlog.BinlogType (*Binlog)(nil), // 1: go.pkg.binlog.Binlog (*Binlog_DBLog)(nil), // 2: go.pkg.binlog.Binlog.DBLog (*Binlog_FileLog)(nil), // 3: go.pkg.binlog.Binlog.FileLog (*duration.Duration)(nil), // 4: google.protobuf.Duration } var file_pkg_binlog_binlog_proto_depIdxs = []int32{ 0, // 0: go.pkg.binlog.Binlog.binlog_type:type_name -> go.pkg.binlog.BinlogType 4, // 1: go.pkg.binlog.Binlog.max_flush_interval:type_name -> google.protobuf.Duration 4, // 2: go.pkg.binlog.Binlog.flush_timeout:type_name -> google.protobuf.Duration 2, // 3: go.pkg.binlog.Binlog.db_log:type_name -> go.pkg.binlog.Binlog.DBLog 3, // 4: go.pkg.binlog.Binlog.file_log:type_name -> go.pkg.binlog.Binlog.FileLog 4, // 5: go.pkg.binlog.Binlog.FileLog.max_age:type_name -> google.protobuf.Duration 4, // 6: go.pkg.binlog.Binlog.FileLog.rotate_interval:type_name -> google.protobuf.Duration 7, // [7:7] is the sub-list for method output_type 7, // [7:7] is the sub-list for method input_type 7, // [7:7] is the sub-list for extension type_name 7, // [7:7] is the sub-list for extension extendee 0, // [0:7] is the sub-list for field type_name } func init() { file_pkg_binlog_binlog_proto_init() } func file_pkg_binlog_binlog_proto_init() { if File_pkg_binlog_binlog_proto != nil { return } if !protoimpl.UnsafeEnabled { file_pkg_binlog_binlog_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Binlog); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_pkg_binlog_binlog_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Binlog_DBLog); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_pkg_binlog_binlog_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Binlog_FileLog); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_pkg_binlog_binlog_proto_rawDesc, NumEnums: 1, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_pkg_binlog_binlog_proto_goTypes, DependencyIndexes: file_pkg_binlog_binlog_proto_depIdxs, EnumInfos: file_pkg_binlog_binlog_proto_enumTypes, MessageInfos: file_pkg_binlog_binlog_proto_msgTypes, }.Build() File_pkg_binlog_binlog_proto = out.File file_pkg_binlog_binlog_proto_rawDesc = nil file_pkg_binlog_binlog_proto_goTypes = nil file_pkg_binlog_binlog_proto_depIdxs = nil } ================================================ FILE: pkg/binlog/binlog.proto ================================================ syntax = "proto3"; package go.pkg.binlog; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/go.pkg.binlog;binlog"; message Binlog { bool enabled = 1; BinlogType binlog_type = 2; int64 flush_batch_size = 3; google.protobuf.Duration max_flush_interval = 4; google.protobuf.Duration flush_timeout = 5; DBLog db_log = 20; FileLog file_log = 21; message DBLog {} message FileLog { string filepath = 3; google.protobuf.Duration max_age = 4; int64 max_count = 5; google.protobuf.Duration rotate_interval = 6; int64 rotate_size = 7; } } enum BinlogType { BinlogType_DB = 0; BinlogType_File = 1; } ================================================ FILE: pkg/binlog/binlog.yaml ================================================ database: mysql: enabled: true address: "localhost:3306" username: "root" password: "" db_name: "sealet" max_connections: 100 max_idle_connections: 10 dial_timeout: 5s max_wait_duration: 20s fail_after_duration: 100s interpolate_params: true mq: kafka: enabled: true brokers: ["localhost:9092"] max_wait_duration: 5s fail_after_duration: 30s binlog: enabled: true binlog_type: "BinlogType_DB" flush_batch_size: 1 flush_timeout: 10s file_log: filepath: ./binlog rotate_interval: 3600s #1h rotate_size: 104857600 #100M ================================================ FILE: pkg/binlog/binlog_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 binlog // A BinlogServiceOption sets options. type BinlogServiceOption interface { apply(*BinlogService) } // EmptyBinlogServiceUrlOption does not alter the BinlogServiceuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyBinlogServiceOption struct{} func (EmptyBinlogServiceOption) apply(*BinlogService) {} // BinlogServiceOptionFunc wraps a function that modifies BinlogService into an // implementation of the BinlogServiceOption interface. type BinlogServiceOptionFunc func(*BinlogService) func (f BinlogServiceOptionFunc) apply(do *BinlogService) { f(do) } // sample code for option, default for nothing to change func _BinlogServiceOptionWithDefault() BinlogServiceOption { return BinlogServiceOptionFunc(func(*BinlogService) { // nothing to change }) } func (o *BinlogService) ApplyOptions(options ...BinlogServiceOption) *BinlogService { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/binlog/binlog_test.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 binlog_test import ( "context" "database/sql" "testing" "encoding/json" "github.com/google/uuid" "github.com/kaydxh/golang/pkg/binlog" binlog_ "github.com/kaydxh/golang/pkg/binlog" ds_ "github.com/kaydxh/golang/pkg/binlog/datastore" mysql_ "github.com/kaydxh/golang/pkg/database/mysql" mq_ "github.com/kaydxh/golang/pkg/mq" kafka_ "github.com/kaydxh/golang/pkg/mq/kafka" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/segmentio/kafka-go" ) type TaskTable struct { // Id sql.NullInt64 `db:"id"` // primary key ID // NullTime represents a time.Time that may be null. // NullTime implements the Scanner interface so // it can be used as a scan destination, similar to NullString. CreateTime sql.NullTime `db:"create_time"` UpdateTime sql.NullTime `db:"update_time"` GroupId string `db:"group_id"` PageId string `db:"page_id"` FeaId string `db:"fea_id"` EntityId string `db:"entity_id"` Feature0 []byte `db:"feature0"` Feature1 []byte `db:"feature1"` ExtendInfo []byte `db:"extend_info"` } func TestProducer(t *testing.T) { cfgFile := "./binlog.yaml" config := kafka_.NewConfig(kafka_.WithViper(viper_.GetViper(cfgFile, "mq.kafka"))) mq, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } topic := "topic-test-1" ctx := context.Background() ps, err := mq.AsProducers(ctx, topic) if err != nil { t.Fatalf("failed to as producers, err: %v", err) } if len(ps) == 0 { t.Fatalf("producers nil") } p := ps[0] tableName := "hetu_zeus_0" cols := []string{"group_id", "page_id", "fea_id", "entity_id", "feature0", "feature1", "extend_info"} msgKey := &ds_.MessageKey{ Key: "Key-A", MsgType: ds_.MsgType_Insert, Fields: cols, Path: tableName, } keyData, _ := json.Marshal(msgKey) for i := 0; i < 10; i++ { arg := &TaskTable{ GroupId: "groupId-1", PageId: "100", FeaId: uuid.NewString(), Feature0: []byte("Feature0"), Feature1: []byte("Feature1"), ExtendInfo: []byte("ExtendInfo"), } msgValue, _ := json.Marshal(arg) err = p.Send(ctx, kafka.Message{ Key: keyData, Value: msgValue, }, ) if err != nil { t.Fatalf("failed to send messages, err: %v", err) } } } func TestNewBinlog(t *testing.T) { // install kafka cfgFile := "./binlog.yaml" config := kafka_.NewConfig(kafka_.WithViper(viper_.GetViper(cfgFile, "mq.kafka"))) mq, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } ctx := context.Background() topic := "topic-test-1" _, err = mq.AsConsumers(ctx, topic) if err != nil { t.Fatalf("failed to as producers, err: %v", err) } consumer, err := mq.GetConsumer(topic) if err != nil { t.Fatalf("failed to get producer, err: %v", err) } dbConfig := mysql_.NewConfig(mysql_.WithViper(viper_.GetViper(cfgFile, "database.mysql"))) db, err := dbConfig.Complete().New(context.Background()) if err != nil { panic(err) } if db == nil { panic("db is not enable") } bsConfig := binlog_.NewConfig(binlog_.WithViper(viper_.GetViper(cfgFile, "binlog"))) bs, err := bsConfig.Complete().New(context.Background(), nil, []mq_.Consumer{consumer}, binlog.WithMessageDecoderFunc(func(ctx context.Context, data []byte) (interface{}, error) { var arg TaskTable err = json.Unmarshal(data, &arg) if err != nil { return arg, err } return arg, nil }), binlog_.WithMessageKeyDecodeFunc(func(ctx context.Context, data []byte) (ds_.MessageKey, error) { var msgKey ds_.MessageKey err := json.Unmarshal(data, &msgKey) return msgKey, err })) if err != nil { panic(err) } _ = bs select {} } ================================================ FILE: pkg/binlog/config.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 binlog import ( "context" "fmt" ds_ "github.com/kaydxh/golang/pkg/binlog/datastore" dbstore_ "github.com/kaydxh/golang/pkg/binlog/datastore/dbstore" filestore_ "github.com/kaydxh/golang/pkg/binlog/datastore/filestore" mysql_ "github.com/kaydxh/golang/pkg/database/mysql" rotate_ "github.com/kaydxh/golang/pkg/file-rotate" mq_ "github.com/kaydxh/golang/pkg/mq" taskq_ "github.com/kaydxh/golang/pkg/pool/taskqueue" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) type Config struct { Proto Binlog opts struct { // If set, overrides params below viper *viper.Viper } } type completedConfig struct { *Config completeError error } type CompletedConfig struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig } func (c *completedConfig) New(ctx context.Context, taskq *taskq_.Pool, consumers []mq_.Consumer, opts ...BinlogServiceOption) (*BinlogService, error) { logrus.Infof("Installing BinlogService") if c.completeError != nil { return nil, c.completeError } if !c.Proto.GetEnabled() { logrus.Warnf("BinlogService disenabled") return nil, nil } sqlxDB, err := c.install(ctx, taskq, consumers, opts...) if err != nil { return nil, err } logrus.Infof("Installed BinlogService") return sqlxDB, nil } func (c *completedConfig) install(ctx context.Context, taskq *taskq_.Pool, consumers []mq_.Consumer, opts ...BinlogServiceOption) (*BinlogService, error) { config := &c.Proto var ( dataStore ds_.DataStore err error ) switch config.GetBinlogType() { case BinlogType_BinlogType_DB: db := mysql_.GetDB() if db == nil { return nil, fmt.Errorf("db is not installed") } dataStore, err = dbstore_.NewDBDataStore(db) if err != nil { return nil, fmt.Errorf("db is not installed") } case BinlogType_BinlogType_File: filelogConfig := config.GetFileLog() dataStore, err = filestore_.NewFileDataStore( filelogConfig.GetFilepath(), rotate_.WithRotateSize(filelogConfig.GetRotateSize()), rotate_.WithRotateInterval(filelogConfig.GetRotateInterval().AsDuration()), //rotate_.WithRotateCallback(bs.rotateCallback), ) if err != nil { return nil, err } default: return nil, fmt.Errorf("binlog type %v is not support", config.GetBinlogType()) } bs, err := NewBinlogService(dataStore, taskq, consumers, opts...) if err != nil { return nil, err } err = bs.Run(ctx) return bs, err } // Complete set default ServerRunOptions. func (c *Config) Complete() CompletedConfig { err := c.loadViper() if err != nil { return CompletedConfig{&completedConfig{ Config: c, completeError: err, }} } return CompletedConfig{&completedConfig{Config: c}} } func (c *Config) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, &c.Proto) } return nil } func NewConfig(options ...ConfigOption) *Config { c := &Config{} c.ApplyOptions(options...) return c } ================================================ FILE: pkg/binlog/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 binlog import ( "github.com/spf13/viper" ) func WithViper(v *viper.Viper) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.viper = v }) } ================================================ FILE: pkg/binlog/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 binlog // A ConfigOption sets options. type ConfigOption interface { apply(*Config) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption struct{} func (EmptyConfigOption) apply(*Config) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc func(*Config) func (f ConfigOptionFunc) apply(do *Config) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault() ConfigOption { return ConfigOptionFunc(func(*Config) { // nothing to change }) } func (o *Config) ApplyOptions(options ...ConfigOption) *Config { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/binlog/datastore/data.store.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 datastore import ( "context" ) type DataStore interface { WriteData(ctx context.Context, arg interface{}, key MessageKey) (n int64, err error) } ================================================ FILE: pkg/binlog/datastore/dbstore/db.store.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 dbstore import ( "context" "fmt" "github.com/jmoiron/sqlx" ds_ "github.com/kaydxh/golang/pkg/binlog/datastore" mysql_ "github.com/kaydxh/golang/pkg/database/mysql" ) var _ ds_.DataStore = (*DBDataStore)(nil) type DBDataStore struct { *sqlx.DB insertSql string updateSql string } func NewDBDataStore(db *sqlx.DB) (*DBDataStore, error) { if db == nil { return nil, fmt.Errorf("db is nil") } s := &DBDataStore{} s.DB = db return s, nil } func (s *DBDataStore) WriteData(ctx context.Context, arg interface{}, key ds_.MessageKey) (n int64, err error) { columnsValues := mysql_.BuildNamedColumnsValuesBatch(arg) sql := mysql_.BuildNamedInsertSql(key.Path, key.Fields, len(columnsValues)) n, err = mysql_.ExecContext(ctx, sql, mysql_.BuildNamedColumnsValuesBatch(arg), nil, s.DB) return n, err } ================================================ FILE: pkg/binlog/datastore/filestore/file.store.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 filestore import ( "context" "fmt" "path/filepath" "sync" ds_ "github.com/kaydxh/golang/pkg/binlog/datastore" rotate_ "github.com/kaydxh/golang/pkg/file-rotate" ) var _ ds_.DataStore = (*FileDataStore)(nil) type FileDataStore struct { rotateFiler *rotate_.RotateFiler rotateFilers map[string]*rotate_.RotateFiler //message key -> rotateFilter rotateFilersMu sync.Mutex rootDir string opts []rotate_.RotateFilerOption } func NewFileDataStore(filedir string, options ...rotate_.RotateFilerOption) (*FileDataStore, error) { rotate, err := rotate_.NewRotateFiler(filedir, options...) if err != nil { return nil, err } s := &FileDataStore{ rootDir: filedir, opts: options, } s.rotateFiler = rotate return s, nil } func (s *FileDataStore) WriteData(ctx context.Context, arg interface{}, key ds_.MessageKey) (n int64, err error) { rotateFiler := s.getOrCreate(ctx, key.Key) p, ok := arg.([][]byte) if !ok { return 0, fmt.Errorf("invalid data type") } _, tn, err := rotateFiler.WriteBytesLine(p) return int64(tn), err } func (s *FileDataStore) getOrCreate(ctx context.Context, key string) *rotate_.RotateFiler { if key == "" { return s.rotateFiler } s.rotateFilersMu.Lock() defer s.rotateFilersMu.Unlock() rotateFiler, ok := s.rotateFilers[key] if !ok { rotateFiler, _ = rotate_.NewRotateFiler( filepath.Join(s.rootDir, key), s.opts..., ) s.rotateFilers[key] = rotateFiler } return rotateFiler } ================================================ FILE: pkg/binlog/datastore/message.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 datastore import ( "reflect" "sort" ) type MessageKey struct { Key string MsgType MsgType Fields []string // To db is table name Path string } func (m MessageKey) Equual(s MessageKey) bool { if m.Key != s.Key { return false } if m.MsgType != s.MsgType { return false } if m.Path != s.Path { return false } sort.Strings(m.Fields) sort.Strings(s.Fields) return reflect.DeepEqual(m.Fields, s.Fields) } type Message struct { Key []byte Value []byte } type MsgType int32 const ( MsgType_Insert MsgType = 0 MsgType_Delete MsgType = 1 MsgType_Update MsgType = 2 MsgType_Get MsgType = 3 ) ================================================ FILE: pkg/binlog/go.mod ================================================ module github.com/kaydxh/golang/pkg/binlog go 1.24.0 require ( github.com/golang/protobuf v1.5.4 github.com/google/uuid v1.6.0 github.com/jmoiron/sqlx v1.4.0 github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/kaydxh/golang/pkg/database v0.0.0-00010101000000-000000000000 github.com/kaydxh/golang/pkg/file-rotate v0.0.0-20251125132602-62c26b682228 github.com/kaydxh/golang/pkg/mq v0.0.0-00010101000000-000000000000 github.com/kaydxh/golang/pkg/pool v0.0.0-00010101000000-000000000000 github.com/kaydxh/golang/pkg/storage v0.0.0-00010101000000-000000000000 github.com/kaydxh/golang/pkg/viper v0.0.0-20251125160242-e06b25c89946 github.com/segmentio/kafka-go v0.4.49 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.21.0 golang.org/x/sync v0.19.0 google.golang.org/protobuf v1.36.10 ) require ( filippo.io/edwards25519 v1.1.0 // indirect github.com/aws/aws-sdk-go v1.55.8 // indirect github.com/aws/aws-sdk-go-v2 v1.36.5 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.11 // indirect github.com/aws/aws-sdk-go-v2/config v1.29.17 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.17.70 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.32 // indirect github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.84 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.36 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.36 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.36 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.4 // indirect github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.7.4 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.17 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.17 // indirect github.com/aws/aws-sdk-go-v2/service/s3 v1.84.0 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.25.5 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.30.3 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.34.0 // indirect github.com/aws/smithy-go v1.22.4 // indirect github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.28.0 // indirect github.com/go-redis/redis/v8 v8.11.5 // indirect github.com/go-sql-driver/mysql v1.9.3 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/google/wire v0.6.0 // indirect github.com/googleapis/gax-go/v2 v2.13.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/pkg/file-cleanup v0.0.0-20251125132602-62c26b682228 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/klauspost/compress v1.18.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pierrec/lz4/v4 v4.1.18 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.opencensus.io v0.24.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect gocloud.dev v0.40.0 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect google.golang.org/api v0.195.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect ) replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/pool => ../pool replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/storage => ../storage replace github.com/kaydxh/golang/pkg/database => ../database replace github.com/kaydxh/golang/pkg/mq => ../mq replace github.com/kaydxh/golang/pkg/logs => ../logs replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf ================================================ FILE: pkg/binlog/go.sum ================================================ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.115.1 h1:Jo0SM9cQnSkYfp44+v+NQXHpcHqlnRJk2qxh6yvxxxQ= cloud.google.com/go v0.115.1/go.mod h1:DuujITeaufu3gL68/lOFIirVNJwQeyf5UXyi+Wbgknc= cloud.google.com/go/auth v0.9.1 h1:+pMtLEV2k0AXKvs/tGZojuj6QaioxfUjOpMsG5Gtx+w= cloud.google.com/go/auth v0.9.1/go.mod h1:Sw8ocT5mhhXxFklyhT12Eiy0ed6tTrPMCJjSI8KhYLk= cloud.google.com/go/auth/oauth2adapt v0.2.4 h1:0GWE/FUsXhf6C+jAkWgYm7X9tK8cuEIfy19DBn6B6bY= cloud.google.com/go/auth/oauth2adapt v0.2.4/go.mod h1:jC/jOpwFP6JBxhB3P5Rr0a9HLMC/Pe3eaL4NmdvqPtc= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= cloud.google.com/go/iam v1.1.13 h1:7zWBXG9ERbMLrzQBRhFliAV+kjcRToDTgQT3CTwYyv4= cloud.google.com/go/iam v1.1.13/go.mod h1:K8mY0uSXwEXS30KrnVb+j54LB/ntfZu1dr+4zFMNbus= cloud.google.com/go/storage v1.43.0 h1:CcxnSohZwizt4LCzQHWvBf1/kvtHUn7gk9QERXPyXFs= cloud.google.com/go/storage v1.43.0/go.mod h1:ajvxEa7WmZS1PxvKRq4bq0tFT3vMd502JwstCcYv0Q0= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ= github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk= github.com/aws/aws-sdk-go-v2 v1.36.5 h1:0OF9RiEMEdDdZEMqF9MRjevyxAQcf6gY+E7vwBILFj0= github.com/aws/aws-sdk-go-v2 v1.36.5/go.mod h1:EYrzvCCN9CMUTa5+6lf6MM4tq3Zjp8UhSGR/cBsjai0= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.11 h1:12SpdwU8Djs+YGklkinSSlcrPyj3H4VifVsKf78KbwA= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.11/go.mod h1:dd+Lkp6YmMryke+qxW/VnKyhMBDTYP41Q2Bb+6gNZgY= github.com/aws/aws-sdk-go-v2/config v1.29.17 h1:jSuiQ5jEe4SAMH6lLRMY9OVC+TqJLP5655pBGjmnjr0= github.com/aws/aws-sdk-go-v2/config v1.29.17/go.mod h1:9P4wwACpbeXs9Pm9w1QTh6BwWwJjwYvJ1iCt5QbCXh8= github.com/aws/aws-sdk-go-v2/credentials v1.17.70 h1:ONnH5CM16RTXRkS8Z1qg7/s2eDOhHhaXVd72mmyv4/0= github.com/aws/aws-sdk-go-v2/credentials v1.17.70/go.mod h1:M+lWhhmomVGgtuPOhO85u4pEa3SmssPTdcYpP/5J/xc= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.32 h1:KAXP9JSHO1vKGCr5f4O6WmlVKLFFXgWYAGoJosorxzU= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.32/go.mod h1:h4Sg6FQdexC1yYG9RDnOvLbW1a/P986++/Y/a+GyEM8= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.84 h1:cTXRdLkpBanlDwISl+5chq5ui1d1YWg4PWMR9c3kXyw= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.84/go.mod h1:kwSy5X7tfIHN39uucmjQVs2LvDdXEjQucgQQEqCggEo= github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.36 h1:SsytQyTMHMDPspp+spo7XwXTP44aJZZAC7fBV2C5+5s= github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.36/go.mod h1:Q1lnJArKRXkenyog6+Y+zr7WDpk4e6XlR6gs20bbeNo= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.36 h1:i2vNHQiXUvKhs3quBR6aqlgJaiaexz/aNvdCktW/kAM= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.36/go.mod h1:UdyGa7Q91id/sdyHPwth+043HhmP6yP9MBHgbZM0xo8= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 h1:bIqFDwgGXXN1Kpp99pDOdKMTTb5d2KyU5X/BZxjOkRo= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3/go.mod h1:H5O/EsxDWyU+LP/V8i5sm8cxoZgc2fdNR9bxlOFrQTo= github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.36 h1:GMYy2EOWfzdP3wfVAGXBNKY5vK4K8vMET4sYOYltmqs= github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.36/go.mod h1:gDhdAV6wL3PmPqBhiPbnlS447GoWs8HTTOYef9/9Inw= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.4 h1:CXV68E2dNqhuynZJPB80bhPQwAKqBWVer887figW6Jc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.4/go.mod h1:/xFi9KtvBXP97ppCz1TAEvU1Uf66qvid89rbem3wCzQ= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.7.4 h1:nAP2GYbfh8dd2zGZqFRSMlq+/F6cMPBUuCsGAMkN074= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.7.4/go.mod h1:LT10DsiGjLWh4GbjInf9LQejkYEhBgBCjLG5+lvk4EE= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.17 h1:t0E6FzREdtCsiLIoLCWsYliNsRBgyGD/MCK571qk4MI= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.17/go.mod h1:ygpklyoaypuyDvOM5ujWGrYWpAK3h7ugnmKCU/76Ys4= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.17 h1:qcLWgdhq45sDM9na4cvXax9dyLitn8EYBRl8Ak4XtG4= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.17/go.mod h1:M+jkjBFZ2J6DJrjMv2+vkBbuht6kxJYtJiwoVgX4p4U= github.com/aws/aws-sdk-go-v2/service/s3 v1.84.0 h1:0reDqfEN+tB+sozj2r92Bep8MEwBZgtAXTND1Kk9OXg= github.com/aws/aws-sdk-go-v2/service/s3 v1.84.0/go.mod h1:kUklwasNoCn5YpyAqC/97r6dzTA1SRKJfKq16SXeoDU= github.com/aws/aws-sdk-go-v2/service/sso v1.25.5 h1:AIRJ3lfb2w/1/8wOOSqYb9fUKGwQbtysJ2H1MofRUPg= github.com/aws/aws-sdk-go-v2/service/sso v1.25.5/go.mod h1:b7SiVprpU+iGazDUqvRSLf5XmCdn+JtT1on7uNL6Ipc= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.30.3 h1:BpOxT3yhLwSJ77qIY3DoHAQjZsc4HEGfMCE4NGy3uFg= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.30.3/go.mod h1:vq/GQR1gOFLquZMSrxUK/cpvKCNVYibNyJ1m7JrU88E= github.com/aws/aws-sdk-go-v2/service/sts v1.34.0 h1:NFOJ/NXEGV4Rq//71Hs1jC/NvPs1ezajK+yQmkwnPV0= github.com/aws/aws-sdk-go-v2/service/sts v1.34.0/go.mod h1:7ph2tGpfQvwzgistp2+zga9f+bCjlQJPkPUmMgDSD7w= github.com/aws/smithy-go v1.22.4 h1:uqXzVZNuNexwc/xrh6Tb56u89WDlJY6HS+KC0S4QSjw= github.com/aws/smithy-go v1.22.4/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-replayers/grpcreplay v1.3.0 h1:1Keyy0m1sIpqstQmgz307zhiJ1pV4uIlFds5weTmxbo= github.com/google/go-replayers/grpcreplay v1.3.0/go.mod h1:v6NgKtkijC0d3e3RW8il6Sy5sqRVUwoQa4mHOGEy8DI= github.com/google/go-replayers/httpreplay v1.2.0 h1:VM1wEyyjaoU53BwrOnaf9VhAyQQEEioJvFYxYcLRKzk= github.com/google/go-replayers/httpreplay v1.2.0/go.mod h1:WahEFFZZ7a1P4VM1qEeHy+tME4bwyqPcwWbNlUI1Mcg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= github.com/google/s2a-go v0.1.8 h1:zZDs9gcbt9ZPLV0ndSyQk6Kacx2g/X+SKYovpnz3SMM= github.com/google/s2a-go v0.1.8/go.mod h1:6iNWHTpQ+nfNRN5E00MSdfDwVesa8hhS32PhPO8deJA= github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/wire v0.6.0 h1:HBkoIh4BdSxoyo9PveV8giw7ZsaBOvzWKfcg/6MrVwI= github.com/google/wire v0.6.0/go.mod h1:F4QhpQ9EDIdJ1Mbop/NZBRB+5yrR6qg3BnctaoUk6NA= github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= github.com/googleapis/gax-go/v2 v2.13.0 h1:yitjD5f7jQHhyDsnhKEBU52NdvvdSeGzlAnDPT0hH1s= github.com/googleapis/gax-go/v2 v2.13.0/go.mod h1:Z/fvTZXF8/uw7Xu5GuslPw+bplx6SS338j1Is2S+B7A= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kaydxh/golang/pkg/file-cleanup v0.0.0-20251125132602-62c26b682228 h1:Q0arlJiD7BygvPMDHcvTdg1urHqADnd7P2qk3r2HlyE= github.com/kaydxh/golang/pkg/file-cleanup v0.0.0-20251125132602-62c26b682228/go.mod h1:ML4gUddcaOo55zQ9/m8SxjZYYVTJACriuUFcqs1BEd4= github.com/kaydxh/golang/pkg/file-rotate v0.0.0-20251125132602-62c26b682228 h1:7zmih7dDhXTVDxbWy4Cp0OrSqMdQaQzlRUtCzZXMVgc= github.com/kaydxh/golang/pkg/file-rotate v0.0.0-20251125132602-62c26b682228/go.mod h1:DeGVCOtdDQNg6/hVvPwYqeH0EbGcbFiQcKNvMrD+NyY= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.18 h1:xaKrnTkyoqfh1YItXl56+6KJNVYWlEEPuAQW9xsplYQ= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/segmentio/kafka-go v0.4.49 h1:GJiNX1d/g+kG6ljyJEoi9++PUMdXGAxb7JGPiDCuNmk= github.com/segmentio/kafka-go v0.4.49/go.mod h1:Y1gn60kzLEEaW28YshXyk2+VCUKbJ3Qr6DrnT3i4+9E= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.53.0 h1:9G6E0TXzGFVfTnawRzrPl83iHOAV7L8NJiR8RSGYV1g= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.53.0/go.mod h1:azvtTADFQJA8mX80jIH/akaE7h+dbm/sVuaHqN13w74= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 h1:4K4tsIXefpVJtvA/8srF4V4y0akAoPHkIslgAkjixJA= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0/go.mod h1:jjdQuTGVsXV4vSs+CJ2qYDeDPf9yIJV23qlIzBm73Vg= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= gocloud.dev v0.40.0 h1:f8LgP+4WDqOG/RXoUcyLpeIAGOcAbZrZbDQCUee10ng= gocloud.dev v0.40.0/go.mod h1:drz+VyYNBvrMTW0KZiBAYEdl8lbNZx+OQ7oQvdrFmSQ= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/api v0.195.0 h1:Ude4N8FvTKnnQJHU48RFI40jOBgIrL8Zqr3/QeST6yU= google.golang.org/api v0.195.0/go.mod h1:DOGRWuv3P8TU8Lnz7uQc4hyNqrBpMtD9ppW3wBJurgc= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20240823204242-4ba0660f739c h1:TYOEhrQMrNDTAd2rX9m+WgGr8Ku6YNuj1D7OX6rWSok= google.golang.org/genproto v0.0.0-20240823204242-4ba0660f739c/go.mod h1:2rC5OendXvZ8wGEo/cSLheztrZDZaSoHanUcd1xtZnw= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= ================================================ FILE: pkg/config/config.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 config import ( "github.com/go-playground/validator/v10" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/spf13/viper" "google.golang.org/protobuf/proto" ) // proto.Message is interface type Config[T proto.Message] struct { Proto T Validator *validator.Validate opts struct { viper *viper.Viper } } type completedConfig[T proto.Message] struct { *Config[T] completeError error } // CompletedConfig same as Config, just to swap private object. type CompletedConfig[T proto.Message] struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig[T] } // Validate checks Config. func (c *completedConfig[T]) Validate() error { return c.Validator.Struct(c) } // Complete fills in any fields not set that are required to have valid data. It's mutating the receiver. func (c *Config[T]) Complete() CompletedConfig[T] { err := c.loadViper() if err != nil { return CompletedConfig[T]{ &completedConfig[T]{ Config: c, completeError: err, }} } if c.Validator == nil { c.Validator = validator.New() } return CompletedConfig[T]{&completedConfig[T]{Config: c}} } func (c *Config[T]) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, c.Proto) } return nil } func (c completedConfig[T]) New() (T, error) { var zero T if c.completeError != nil { return zero, c.completeError } return c.Proto, nil } func NewConfig[T proto.Message](value T, options ...ConfigOption[T]) *Config[T] { var c Config[T] c.Proto = value c.ApplyOptions(options...) return &c } ================================================ FILE: pkg/config/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 config import ( "github.com/spf13/viper" "google.golang.org/protobuf/proto" ) func WithViper[T proto.Message](v *viper.Viper) ConfigOption[T] { return ConfigOptionFunc[T](func(c *Config[T]) { c.opts.viper = v }) } ================================================ FILE: pkg/config/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 config import "google.golang.org/protobuf/proto" // A ConfigOption sets options. type ConfigOption[T proto.Message] interface { apply(*Config[T]) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption[T proto.Message] struct{} func (EmptyConfigOption[T]) apply(*Config[T]) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc[T proto.Message] func(*Config[T]) func (f ConfigOptionFunc[T]) apply(do *Config[T]) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault[T proto.Message]() ConfigOption[T] { return ConfigOptionFunc[T](func(*Config[T]) { // nothing to change }) } func (o *Config[T]) ApplyOptions(options ...ConfigOption[T]) *Config[T] { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/config/go.mod ================================================ module github.com/kaydxh/golang/pkg/config go 1.24.0 replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf require ( github.com/go-playground/validator/v10 v10.28.0 github.com/kaydxh/golang/pkg/viper v0.0.0-00010101000000-000000000000 github.com/spf13/viper v1.21.0 google.golang.org/protobuf v1.36.10 ) require ( github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect ) ================================================ FILE: pkg/config/go.sum ================================================ github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: pkg/container/docker/docker.proto ================================================ syntax = "proto3"; package go.pkg.container.docker; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/go.pkg.container.docker;docker"; message Docker { bool enabled = 1; string address = 2; } ================================================ FILE: pkg/container/go.mod ================================================ module github.com/kaydxh/golang/pkg/container go 1.24.0 replace github.com/kaydxh/golang/go => ../../go ================================================ FILE: pkg/container/go.sum ================================================ ================================================ FILE: pkg/crontab/config.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 crontab import ( "context" "github.com/go-playground/validator/v10" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) // Config ... type Config struct { Proto Crontab Validator *validator.Validate opts struct { // If set, overrides params below viper *viper.Viper } } type completedConfig struct { *Config completeError error } // CompletedConfig ... type CompletedConfig struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig } func (c *completedConfig) New(ctx context.Context) (*CrontabSerivce, error) { logrus.Infof("Installing Crontab") if c.completeError != nil { return nil, c.completeError } if !c.Proto.GetEnabled() { return nil, nil } rs, err := c.install(ctx) if err != nil { return nil, err } logrus.Infof("Installed Crontab") return rs, nil } func (c *completedConfig) install(ctx context.Context) (*CrontabSerivce, error) { checkInterval := c.Proto.GetCheckInterval().AsDuration() rs := NewCrontabSerivce(checkInterval) return rs, nil } // Validate checks Config. func (c *completedConfig) Validate() error { return c.Validator.Struct(c) } // Complete fills in any fields not set that are required to have valid data and can be derived // from other fields. If you're going to `ApplyOptions`, do that first. It's mutating the receiver. func (c *Config) Complete() CompletedConfig { err := c.loadViper() if err != nil { return CompletedConfig{&completedConfig{ Config: c, completeError: err, }} } return CompletedConfig{&completedConfig{Config: c}} } func (c *Config) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, &c.Proto) } return nil } // NewConfig returns a Config struct with the default values func NewConfig(options ...ConfigOption) *Config { c := &Config{} c.ApplyOptions(options...) return c } ================================================ FILE: pkg/crontab/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 crontab import ( "github.com/spf13/viper" ) func WithViper(v *viper.Viper) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.viper = v }) } ================================================ FILE: pkg/crontab/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 crontab // A ConfigOption sets options. type ConfigOption interface { apply(*Config) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption struct{} func (EmptyConfigOption) apply(*Config) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc func(*Config) func (f ConfigOptionFunc) apply(do *Config) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault() ConfigOption { return ConfigOptionFunc(func(*Config) { // nothing to change }) } func (o *Config) ApplyOptions(options ...ConfigOption) *Config { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/crontab/crontab.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 crontab import ( "context" "fmt" "sync" "time" "github.com/kaydxh/golang/go/errors" errors_ "github.com/kaydxh/golang/go/errors" time_ "github.com/kaydxh/golang/go/time" "github.com/sirupsen/logrus" "go.uber.org/atomic" ) // Crontab ... type CrontabSerivce struct { checkInterval time.Duration inShutdown atomic.Bool // true when when server is in shutdown mu sync.Mutex cancel func() fs []func(context.Context, *logrus.Entry) error } // NewCrontab ... func NewCrontabSerivce( checkInterval time.Duration, ) *CrontabSerivce { s := &CrontabSerivce{ checkInterval: checkInterval, } return s } // Register ... func (c *CrontabSerivce) Register(f func(context.Context, *logrus.Entry) error) { c.fs = append(c.fs, f) } // Run will initialize the backend. It must not block, but may run go routines in the background. func (c *CrontabSerivce) Run(ctx context.Context) error { logger := c.getLogger() logger.Infoln("Crontab Run") if c.inShutdown.Load() { logger.Infoln("Crontab Shutdown") return fmt.Errorf("server closed") } go func() { errors.HandleError(c.Serve(ctx)) }() return nil } // Serve ... func (c *CrontabSerivce) Serve(ctx context.Context) error { logger := c.getLogger() logger.Infoln("Crontab Serve") if c.inShutdown.Load() { logger.Infoln("Crontab Shutdown") return fmt.Errorf("server closed") } defer c.inShutdown.Store(true) ctx, cancel := context.WithCancel(ctx) defer cancel() c.mu.Lock() c.cancel = cancel c.mu.Unlock() time_.UntilWithContxt(ctx, func(ctx context.Context) error { err := c.check(ctx) if err != nil { return err } return nil }, c.checkInterval) if err := ctx.Err(); err != nil { logger.WithError(err).Errorf("stopped checking") return err } logger.Info("stopped checking") return nil } // Shutdown ... func (c *CrontabSerivce) Shutdown() { c.inShutdown.Store(true) c.mu.Lock() defer c.mu.Unlock() if c.cancel != nil { c.cancel() } } func (c *CrontabSerivce) getLogger() *logrus.Entry { return logrus.WithField("module", "Crontab") } func (c *CrontabSerivce) check(ctx context.Context) error { var ( wg sync.WaitGroup errs []error ) logger := c.getLogger() c.mu.Lock() fs := c.fs c.mu.Unlock() for _, f := range fs { wg.Add(1) go func(doFunc func(context.Context, *logrus.Entry) error) { defer wg.Done() err := doFunc(ctx, logger) if err != nil { c.mu.Lock() errs = append(errs, err) c.mu.Unlock() } }(f) } wg.Wait() return errors_.NewAggregate(errs) } /* type CronProcessor struct { cronRunner *cron.Cron } type Job interface { Run() } func NewCronProcessor(specTime string, job Job) (*CronProcessor, error) { cp := &CronProcessor{ cronRunner: cron.New(), } if cp.cronRunner == nil { return nil, fmt.Errorf("failed to init cronRunner") } if specTime == "" { return nil, fmt.Errorf("specTime is empty") } err := cp.cronRunner.AddJob(specTime, job) if err != nil { return nil, fmt.Errorf("failed to odd job in specTime: [%v]", specTime) } cp.cronRunner.Start() return cp, nil } func (c *CronProcessor) Stop() { c.cronRunner.Stop() } */ ================================================ FILE: pkg/crontab/crontab.pb.go ================================================ /* *Copyright (c) 2022, kaydxh * *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. */ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 // protoc v3.13.0 // source: pkg/crontab/crontab.proto package crontab import ( duration "github.com/golang/protobuf/ptypes/duration" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Crontab struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` CheckInterval *duration.Duration `protobuf:"bytes,4,opt,name=check_interval,json=checkInterval,proto3" json:"check_interval,omitempty"` } func (x *Crontab) Reset() { *x = Crontab{} if protoimpl.UnsafeEnabled { mi := &file_pkg_crontab_crontab_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Crontab) String() string { return protoimpl.X.MessageStringOf(x) } func (*Crontab) ProtoMessage() {} func (x *Crontab) ProtoReflect() protoreflect.Message { mi := &file_pkg_crontab_crontab_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Crontab.ProtoReflect.Descriptor instead. func (*Crontab) Descriptor() ([]byte, []int) { return file_pkg_crontab_crontab_proto_rawDescGZIP(), []int{0} } func (x *Crontab) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *Crontab) GetCheckInterval() *duration.Duration { if x != nil { return x.CheckInterval } return nil } var File_pkg_crontab_crontab_proto protoreflect.FileDescriptor var file_pkg_crontab_crontab_proto_rawDesc = []byte{ 0x0a, 0x19, 0x70, 0x6b, 0x67, 0x2f, 0x63, 0x72, 0x6f, 0x6e, 0x74, 0x61, 0x62, 0x2f, 0x63, 0x72, 0x6f, 0x6e, 0x74, 0x61, 0x62, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0e, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x63, 0x72, 0x6f, 0x6e, 0x74, 0x61, 0x62, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x65, 0x0a, 0x07, 0x43, 0x72, 0x6f, 0x6e, 0x74, 0x61, 0x62, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x40, 0x0a, 0x0e, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x42, 0x2a, 0x5a, 0x28, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x63, 0x72, 0x6f, 0x6e, 0x74, 0x61, 0x62, 0x3b, 0x63, 0x72, 0x6f, 0x6e, 0x74, 0x61, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_pkg_crontab_crontab_proto_rawDescOnce sync.Once file_pkg_crontab_crontab_proto_rawDescData = file_pkg_crontab_crontab_proto_rawDesc ) func file_pkg_crontab_crontab_proto_rawDescGZIP() []byte { file_pkg_crontab_crontab_proto_rawDescOnce.Do(func() { file_pkg_crontab_crontab_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_crontab_crontab_proto_rawDescData) }) return file_pkg_crontab_crontab_proto_rawDescData } var file_pkg_crontab_crontab_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_pkg_crontab_crontab_proto_goTypes = []interface{}{ (*Crontab)(nil), // 0: go.pkg.crontab.Crontab (*duration.Duration)(nil), // 1: google.protobuf.Duration } var file_pkg_crontab_crontab_proto_depIdxs = []int32{ 1, // 0: go.pkg.crontab.Crontab.check_interval:type_name -> google.protobuf.Duration 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_pkg_crontab_crontab_proto_init() } func file_pkg_crontab_crontab_proto_init() { if File_pkg_crontab_crontab_proto != nil { return } if !protoimpl.UnsafeEnabled { file_pkg_crontab_crontab_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Crontab); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_pkg_crontab_crontab_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_pkg_crontab_crontab_proto_goTypes, DependencyIndexes: file_pkg_crontab_crontab_proto_depIdxs, MessageInfos: file_pkg_crontab_crontab_proto_msgTypes, }.Build() File_pkg_crontab_crontab_proto = out.File file_pkg_crontab_crontab_proto_rawDesc = nil file_pkg_crontab_crontab_proto_goTypes = nil file_pkg_crontab_crontab_proto_depIdxs = nil } ================================================ FILE: pkg/crontab/crontab.proto ================================================ syntax = "proto3"; package go.pkg.crontab; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/go.pkg.crontab;crontab"; message Crontab { bool enabled = 1; google.protobuf.Duration check_interval = 4; } ================================================ FILE: pkg/crontab/crontab.yaml ================================================ crontab: enabled: true check_interval : 10s ================================================ FILE: pkg/crontab/crontab_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 crontab_test import ( "context" "os" "path/filepath" "testing" "time" crontab_ "github.com/kaydxh/golang/pkg/crontab" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" ) func TestCrontabSerivce(t *testing.T) { cfgFile := "./crontab.yaml" config := crontab_.NewConfig(crontab_.WithViper(viper_.GetViper(cfgFile, "crontab"))) s, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } s.Run(context.Background()) s.Register(func(ctx context.Context, logger *logrus.Entry) error { logger.Infof("doing...") filepath.Walk("./testdata", func(path string, info os.FileInfo, err error) error { if !info.IsDir() { now := time.Now() if now.Sub(info.ModTime()) > time.Minute { t.Logf("file[%v] expired 1 Minute, modify time: %v, now: %v", path, info.ModTime(), now) } else { t.Logf("file[%v] normal, modify time: %v, now: %v", path, info.ModTime(), now) } } return nil }) return nil }) time.Sleep(1 * time.Minute) } ================================================ FILE: pkg/crontab/go.mod ================================================ module github.com/kaydxh/golang/pkg/crontab go 1.24.0 replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf require ( github.com/go-playground/validator/v10 v10.28.0 github.com/golang/protobuf v1.5.4 github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/kaydxh/golang/pkg/viper v0.0.0-00010101000000-000000000000 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.21.0 go.uber.org/atomic v1.11.0 google.golang.org/protobuf v1.36.10 ) require ( github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect ) ================================================ FILE: pkg/crontab/go.sum ================================================ github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= ================================================ FILE: pkg/crontab/testdata/1.txt ================================================ 1 ================================================ FILE: pkg/crontab/testdata/2.txt ================================================ 2 ================================================ FILE: pkg/crontab/testdata/3.txt ================================================ 3 ================================================ FILE: pkg/database/db.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 database import ( "time" ) var ( ExecuteTimeout = time.Minute ) ================================================ FILE: pkg/database/go.mod ================================================ module github.com/kaydxh/golang/pkg/database go 1.24.0 replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf require ( github.com/go-redis/redis/v8 v8.11.5 github.com/go-sql-driver/mysql v1.9.3 github.com/golang/protobuf v1.5.4 github.com/google/uuid v1.6.0 github.com/jmoiron/sqlx v1.4.0 github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/kaydxh/golang/pkg/viper v0.0.0-00010101000000-000000000000 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 google.golang.org/protobuf v1.36.10 ) require ( filippo.io/edwards25519 v1.1.0 // indirect github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.28.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/onsi/gomega v1.35.1 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) ================================================ FILE: pkg/database/go.sum ================================================ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= ================================================ FILE: pkg/database/mysql/config.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql import ( "context" "github.com/jmoiron/sqlx" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) type Config struct { Proto Mysql opts struct { // If set, overrides params below viper *viper.Viper } } type completedConfig struct { *Config completeError error } type CompletedConfig struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig } func (c *completedConfig) New(ctx context.Context) (*sqlx.DB, error) { logrus.Infof("Installing Mysql") if c.completeError != nil { return nil, c.completeError } if !c.Proto.GetEnabled() { logrus.Warnf("Mysql disenabled") return nil, nil } sqlxDB, err := c.install(ctx) if err != nil { return nil, err } logrus.Infof("Installed Mysql") return sqlxDB, nil } func (c *completedConfig) install(ctx context.Context) (*sqlx.DB, error) { db := NewDB( DBConfig{ Address: c.Proto.GetAddress(), DataName: c.Proto.GetDbName(), UserName: c.Proto.GetUsername(), Password: c.Proto.GetPassword(), }, WithMaxConnections(int(c.Proto.GetMaxConnections())), WithMaxIdleConnections(int(c.Proto.GetMaxIdleConnections())), WithDialTimeout(c.Proto.GetDialTimeout().AsDuration()), WithReadTimeout(c.Proto.GetReadTimeout().AsDuration()), WithWriteTimeout(c.Proto.GetWriteTimeout().AsDuration()), WithConnMaxLifetime(c.Proto.GetMaxLifeTime().AsDuration()), WithInterpolateParams(c.Proto.GetInterpolateParams()), ) return db.GetDatabaseUntil( ctx, c.Proto.GetMaxWaitDuration().AsDuration(), c.Proto.GetFailAfterDuration().AsDuration(), ) } // Complete set default ServerRunOptions. func (c *Config) Complete() CompletedConfig { err := c.loadViper() if err != nil { return CompletedConfig{&completedConfig{ Config: c, completeError: err, }} } return CompletedConfig{&completedConfig{Config: c}} } func (c *Config) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, &c.Proto) } return nil } func NewConfig(options ...ConfigOption) *Config { c := &Config{} c.ApplyOptions(options...) return c } ================================================ FILE: pkg/database/mysql/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql import ( "github.com/spf13/viper" ) func WithViper(v *viper.Viper) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.viper = v }) } ================================================ FILE: pkg/database/mysql/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql // A ConfigOption sets options. type ConfigOption interface { apply(*Config) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption struct{} func (EmptyConfigOption) apply(*Config) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc func(*Config) func (f ConfigOptionFunc) apply(do *Config) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault() ConfigOption { return ConfigOptionFunc(func(*Config) { // nothing to change }) } func (o *Config) ApplyOptions(options ...ConfigOption) *Config { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/database/mysql/migrate/rename_db.sql ================================================ delimiter ;; CREATE DATABASE /*!32312 IF NOT EXISTS*/ `new_db_name` /*!40100 DEFAULT CHARACTER SET utf8*/; USE `new_db_name`; SET @queryCount = ( SELECT COUNT(*) FROM information_schema.TABLES WHERE table_schema IN ('old_db_name')); DROP PROCEDURE IF EXISTS test_move; CREATE PROCEDURE test_move () BEGIN DECLARE i INT DEFAULT 0; WHILE i < @queryCount DO SET @queryString := ( SELECT CONCAT('RENAME TABLE ',table_schema,'.',table_name, ' TO ','new_db_name.',table_name,';') FROM information_schema.TABLES WHERE table_schema IN ('old_db_name') ORDER BY table_name LIMIT 1 ); PREPARE stmt FROM @queryString; SELECT @queryString as ``; SELECT i as ``; EXECUTE stmt; SET i=i+1; END WHILE ; commit; END;; delimiter ; CALL test_move(); ================================================ FILE: pkg/database/mysql/mysql.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql import ( "context" "fmt" "sync" "time" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" time_ "github.com/kaydxh/golang/go/time" ) var ( sqlDB SQLDB sqlDBs map[DBConfig]SQLDB mu sync.Mutex ) // Default values for Mysql. const ( DefaultMaxConns = 100 DefaultMaxIdleConns = 10 ) type DBConfig struct { Address string DataName string UserName string Password string } type DB struct { //DSN string Conf DBConfig db *sqlx.DB opts struct { maxConns int maxIdleConns int dialTimeout time.Duration readTimeout time.Duration writeTimeout time.Duration // connection reused time, 0 means never expired connMaxLifetime time.Duration interpolateParams bool } } func NewDB(conf DBConfig, opts ...DBOption) *DB { conn := &DB{ Conf: conf, } conn.opts.maxConns = DefaultMaxConns conn.opts.maxIdleConns = DefaultMaxIdleConns conn.ApplyOptions(opts...) return conn } func GetDB() *sqlx.DB { return sqlDB.Load() } func GetTheDB(conf DBConfig) (*sqlx.DB, error) { mu.Lock() defer mu.Unlock() sqlDB, ok := sqlDBs[conf] if !ok { return nil, fmt.Errorf("not found the db in cache") } return sqlDB.Load(), nil } func CloseDB() error { if sqlDB.Load() == nil { return nil } return sqlDB.Load().Close() } func CloseTheDB(conf DBConfig) error { mu.Lock() defer mu.Unlock() sqlDB, ok := sqlDBs[conf] if !ok { return fmt.Errorf("not found the db in cache") } if sqlDB.Load() == nil { return nil } err := sqlDB.Load().Close() if err != nil { return err } delete(sqlDBs, conf) return nil } func (d *DB) GetDatabase() (*sqlx.DB, error) { if d.db != nil { return d.db, nil } dsn := fmt.Sprintf( "%s:%s@tcp(%s)/%s?charset=utf8&loc=Local&parseTime=true", d.Conf.UserName, d.Conf.Password, d.Conf.Address, d.Conf.DataName, ) dsnFull := fmt.Sprintf("%s%s", dsn, func() string { var params string if d.opts.dialTimeout > 0 { params += fmt.Sprintf("&timeout=%fs", d.opts.dialTimeout.Seconds()) } if d.opts.readTimeout > 0 { params += fmt.Sprintf("&readTimeout=%fs", d.opts.readTimeout.Seconds()) } if d.opts.writeTimeout > 0 { params += fmt.Sprintf("&writeTimeout=%fs", d.opts.writeTimeout.Seconds()) } if d.opts.interpolateParams { params += "&interpolateParams=true" } else { params += "&interpolateParams=false" } return params }()) db, err := sqlx.Open("mysql", dsnFull) if err != nil { return nil, err } if err := db.Ping(); err != nil { return nil, err } db.SetMaxOpenConns(d.opts.maxConns) db.SetMaxIdleConns(d.opts.maxIdleConns) db.SetConnMaxLifetime(d.opts.connMaxLifetime) d.db = db sqlDB.Store(db) mu.Lock() defer mu.Unlock() if sqlDBs == nil { sqlDBs = make(map[DBConfig]SQLDB) } sqlDBs[d.Conf] = sqlDB return d.db, nil } func (d *DB) GetDatabaseUntil( ctx context.Context, maxWaitInterval time.Duration, failAfter time.Duration, ) (*sqlx.DB, error) { var db *sqlx.DB exp := time_.NewExponentialBackOff( time_.WithExponentialBackOffOptionMaxInterval(maxWaitInterval), time_.WithExponentialBackOffOptionMaxElapsedTime(failAfter), ) err := time_.BackOffUntilWithContext(ctx, func(ctx context.Context) (err_ error) { db, err_ = d.GetDatabase() if err_ != nil { return err_ } return nil }, exp, true, false) if err != nil { return nil, fmt.Errorf("get database fail after: %v", failAfter) } return db, nil } func (d *DB) Close() error { if d.db == nil { return fmt.Errorf("no database pool") } return d.db.Close() } ================================================ FILE: pkg/database/mysql/mysql.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql import ( "time" ) func WithMaxConnections(maxConns int) DBOption { return DBOptionFunc(func(c *DB) { c.opts.maxConns = maxConns }) } func WithMaxIdleConnections(maxIdleConns int) DBOption { return DBOptionFunc(func(c *DB) { c.opts.maxIdleConns = maxIdleConns }) } func WithDialTimeout(dialTimeout time.Duration) DBOption { return DBOptionFunc(func(c *DB) { c.opts.dialTimeout = dialTimeout }) } func WithReadTimeout(readTimeout time.Duration) DBOption { return DBOptionFunc(func(c *DB) { c.opts.readTimeout = readTimeout }) } func WithWriteTimeout(writeTimeout time.Duration) DBOption { return DBOptionFunc(func(c *DB) { c.opts.writeTimeout = writeTimeout }) } func WithConnMaxLifetime(connMaxLifetime time.Duration) DBOption { return DBOptionFunc(func(c *DB) { c.opts.connMaxLifetime = connMaxLifetime }) } func WithInterpolateParams(enabled bool) DBOption { return DBOptionFunc(func(c *DB) { c.opts.interpolateParams = enabled }) } ================================================ FILE: pkg/database/mysql/mysql.pb.go ================================================ /* *Copyright (c) 2022, kaydxh * *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. */ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 // protoc v3.13.0 // source: pkg/database/mysql/mysql.proto package mysql import ( duration "github.com/golang/protobuf/ptypes/duration" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Mysql struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` Username string `protobuf:"bytes,3,opt,name=username,proto3" json:"username,omitempty"` Password string `protobuf:"bytes,4,opt,name=password,proto3" json:"password,omitempty"` DbName string `protobuf:"bytes,5,opt,name=db_name,json=dbName,proto3" json:"db_name,omitempty"` MaxConnections int32 `protobuf:"varint,6,opt,name=max_connections,json=maxConnections,proto3" json:"max_connections,omitempty"` MaxIdleConnections int32 `protobuf:"varint,7,opt,name=max_idle_connections,json=maxIdleConnections,proto3" json:"max_idle_connections,omitempty"` DialTimeout *duration.Duration `protobuf:"bytes,8,opt,name=dial_timeout,json=dialTimeout,proto3" json:"dial_timeout,omitempty"` ReadTimeout *duration.Duration `protobuf:"bytes,9,opt,name=read_timeout,json=readTimeout,proto3" json:"read_timeout,omitempty"` // https://github.com/go-sql-driver/mysql#writetimeout WriteTimeout *duration.Duration `protobuf:"bytes,10,opt,name=write_timeout,json=writeTimeout,proto3" json:"write_timeout,omitempty"` MaxLifeTime *duration.Duration `protobuf:"bytes,11,opt,name=max_life_time,json=maxLifeTime,proto3" json:"max_life_time,omitempty"` MaxWaitDuration *duration.Duration `protobuf:"bytes,12,opt,name=max_wait_duration,json=maxWaitDuration,proto3" json:"max_wait_duration,omitempty"` FailAfterDuration *duration.Duration `protobuf:"bytes,13,opt,name=fail_after_duration,json=failAfterDuration,proto3" json:"fail_after_duration,omitempty"` InterpolateParams bool `protobuf:"varint,14,opt,name=interpolate_params,json=interpolateParams,proto3" json:"interpolate_params,omitempty"` } func (x *Mysql) Reset() { *x = Mysql{} if protoimpl.UnsafeEnabled { mi := &file_pkg_database_mysql_mysql_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Mysql) String() string { return protoimpl.X.MessageStringOf(x) } func (*Mysql) ProtoMessage() {} func (x *Mysql) ProtoReflect() protoreflect.Message { mi := &file_pkg_database_mysql_mysql_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Mysql.ProtoReflect.Descriptor instead. func (*Mysql) Descriptor() ([]byte, []int) { return file_pkg_database_mysql_mysql_proto_rawDescGZIP(), []int{0} } func (x *Mysql) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *Mysql) GetAddress() string { if x != nil { return x.Address } return "" } func (x *Mysql) GetUsername() string { if x != nil { return x.Username } return "" } func (x *Mysql) GetPassword() string { if x != nil { return x.Password } return "" } func (x *Mysql) GetDbName() string { if x != nil { return x.DbName } return "" } func (x *Mysql) GetMaxConnections() int32 { if x != nil { return x.MaxConnections } return 0 } func (x *Mysql) GetMaxIdleConnections() int32 { if x != nil { return x.MaxIdleConnections } return 0 } func (x *Mysql) GetDialTimeout() *duration.Duration { if x != nil { return x.DialTimeout } return nil } func (x *Mysql) GetReadTimeout() *duration.Duration { if x != nil { return x.ReadTimeout } return nil } func (x *Mysql) GetWriteTimeout() *duration.Duration { if x != nil { return x.WriteTimeout } return nil } func (x *Mysql) GetMaxLifeTime() *duration.Duration { if x != nil { return x.MaxLifeTime } return nil } func (x *Mysql) GetMaxWaitDuration() *duration.Duration { if x != nil { return x.MaxWaitDuration } return nil } func (x *Mysql) GetFailAfterDuration() *duration.Duration { if x != nil { return x.FailAfterDuration } return nil } func (x *Mysql) GetInterpolateParams() bool { if x != nil { return x.InterpolateParams } return false } var File_pkg_database_mysql_mysql_proto protoreflect.FileDescriptor var file_pkg_database_mysql_mysql_proto_rawDesc = []byte{ 0x0a, 0x1e, 0x70, 0x6b, 0x67, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x2f, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xa3, 0x05, 0x0a, 0x05, 0x4d, 0x79, 0x73, 0x71, 0x6c, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x64, 0x62, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x64, 0x62, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0e, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x30, 0x0a, 0x14, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x64, 0x6c, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x05, 0x52, 0x12, 0x6d, 0x61, 0x78, 0x49, 0x64, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x3c, 0x0a, 0x0c, 0x64, 0x69, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x3c, 0x0a, 0x0c, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x72, 0x65, 0x61, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x3e, 0x0a, 0x0d, 0x77, 0x72, 0x69, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x77, 0x72, 0x69, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x3d, 0x0a, 0x0d, 0x6d, 0x61, 0x78, 0x5f, 0x6c, 0x69, 0x66, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x6d, 0x61, 0x78, 0x4c, 0x69, 0x66, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x45, 0x0a, 0x11, 0x6d, 0x61, 0x78, 0x5f, 0x77, 0x61, 0x69, 0x74, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x6d, 0x61, 0x78, 0x57, 0x61, 0x69, 0x74, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x49, 0x0a, 0x13, 0x66, 0x61, 0x69, 0x6c, 0x5f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x11, 0x66, 0x61, 0x69, 0x6c, 0x41, 0x66, 0x74, 0x65, 0x72, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2d, 0x0a, 0x12, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x6f, 0x6c, 0x61, 0x74, 0x65, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x6f, 0x6c, 0x61, 0x74, 0x65, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x42, 0x2f, 0x5a, 0x2d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x3b, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_pkg_database_mysql_mysql_proto_rawDescOnce sync.Once file_pkg_database_mysql_mysql_proto_rawDescData = file_pkg_database_mysql_mysql_proto_rawDesc ) func file_pkg_database_mysql_mysql_proto_rawDescGZIP() []byte { file_pkg_database_mysql_mysql_proto_rawDescOnce.Do(func() { file_pkg_database_mysql_mysql_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_database_mysql_mysql_proto_rawDescData) }) return file_pkg_database_mysql_mysql_proto_rawDescData } var file_pkg_database_mysql_mysql_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_pkg_database_mysql_mysql_proto_goTypes = []interface{}{ (*Mysql)(nil), // 0: go.pkg.database.mysql.Mysql (*duration.Duration)(nil), // 1: google.protobuf.Duration } var file_pkg_database_mysql_mysql_proto_depIdxs = []int32{ 1, // 0: go.pkg.database.mysql.Mysql.dial_timeout:type_name -> google.protobuf.Duration 1, // 1: go.pkg.database.mysql.Mysql.read_timeout:type_name -> google.protobuf.Duration 1, // 2: go.pkg.database.mysql.Mysql.write_timeout:type_name -> google.protobuf.Duration 1, // 3: go.pkg.database.mysql.Mysql.max_life_time:type_name -> google.protobuf.Duration 1, // 4: go.pkg.database.mysql.Mysql.max_wait_duration:type_name -> google.protobuf.Duration 1, // 5: go.pkg.database.mysql.Mysql.fail_after_duration:type_name -> google.protobuf.Duration 6, // [6:6] is the sub-list for method output_type 6, // [6:6] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_pkg_database_mysql_mysql_proto_init() } func file_pkg_database_mysql_mysql_proto_init() { if File_pkg_database_mysql_mysql_proto != nil { return } if !protoimpl.UnsafeEnabled { file_pkg_database_mysql_mysql_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Mysql); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_pkg_database_mysql_mysql_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_pkg_database_mysql_mysql_proto_goTypes, DependencyIndexes: file_pkg_database_mysql_mysql_proto_depIdxs, MessageInfos: file_pkg_database_mysql_mysql_proto_msgTypes, }.Build() File_pkg_database_mysql_mysql_proto = out.File file_pkg_database_mysql_mysql_proto_rawDesc = nil file_pkg_database_mysql_mysql_proto_goTypes = nil file_pkg_database_mysql_mysql_proto_depIdxs = nil } ================================================ FILE: pkg/database/mysql/mysql.proto ================================================ syntax = "proto3"; package go.pkg.database.mysql; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/go.pkg.database.mysql;mysql"; message Mysql { bool enabled = 1; string address = 2; string username = 3; string password = 4; string db_name = 5; int32 max_connections = 6; int32 max_idle_connections = 7; google.protobuf.Duration dial_timeout = 8; google.protobuf.Duration read_timeout = 9; // https://github.com/go-sql-driver/mysql#writetimeout google.protobuf.Duration write_timeout = 10; google.protobuf.Duration max_life_time = 11; google.protobuf.Duration max_wait_duration = 12; google.protobuf.Duration fail_after_duration = 13; bool interpolate_params = 14; } ================================================ FILE: pkg/database/mysql/mysql.yaml ================================================ database: mysql: enabled: true address: "localhost:3306" username: "root" password: "12345" db_name: "sealet" max_connections: 100 max_idle_connections: 10 dial_timeout: 5s max_wait_duration: 20s fail_after_duration: 60s interpolate_params: true ================================================ FILE: pkg/database/mysql/mysql_operate_test.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 mysql_test import ( "context" "database/sql" "fmt" "strings" "testing" "github.com/google/uuid" mysql_ "github.com/kaydxh/golang/pkg/database/mysql" viper_ "github.com/kaydxh/golang/pkg/viper" ) type TaskTable struct { // Id sql.NullInt64 `db:"id"` // primary key ID // NullTime represents a time.Time that may be null. // NullTime implements the Scanner interface so // it can be used as a scan destination, similar to NullString. CreateTime sql.NullTime `db:"create_time"` UpdateTime sql.NullTime `db:"update_time"` GroupId string `db:"group_id"` PageId string `db:"page_id"` FeaId string `db:"fea_id"` EntityId string `db:"entity_id"` Feature0 []byte `db:"feature0"` Feature1 []byte `db:"feature1"` ExtendInfo []byte `db:"extend_info"` } type Tasks []*TaskTable func (t Tasks) String() string { s := "[" for _, task := range t { s += fmt.Sprintf("%v,", task) } if len(t) > 0 { s = strings.TrimRight(s, ",") } return s + "]" } func TestInsert(t *testing.T) { cfgFile := "./mysql.dev.yaml" config := mysql_.NewConfig(mysql_.WithViper(viper_.GetViper(cfgFile, "database.mysql"))) db, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } t.Logf("db: %#v", db) ctx := context.Background() testCases := []struct { TableName string GroupId string Number int64 }{ { TableName: "hetu_zeus_0", GroupId: "hetu_image_copyright_prod", Number: 100, }, } for _, testCase := range testCases { t.Run(fmt.Sprintf("table[%v]-fieldKey[%v]", testCase.TableName, testCase.GroupId), func(t *testing.T) { count := testCase.Number for count > 0 { arg := &TaskTable{ GroupId: testCase.GroupId, PageId: "100", FeaId: uuid.NewString(), Feature0: []byte("Feature0"), Feature1: []byte("Feature1"), ExtendInfo: []byte("ExtendInfo"), } query := fmt.Sprintf(`INSERT INTO %s ( group_id, page_id, fea_id, entity_id, feature0, feature1, extend_info ) VALUES ( :group_id, :page_id, :fea_id, :entity_id, :feature0, :feature1, :extend_info ) `, testCase.TableName) _, err = mysql_.ExecContext(ctx, query, arg, nil, db) if err != nil { t.Errorf("faild to insert %v, err: %v", arg, err) } count-- } }) } } func TestInsertNewBatch(t *testing.T) { cfgFile := "./mysql.dev.yaml" config := mysql_.NewConfig(mysql_.WithViper(viper_.GetViper(cfgFile, "database.mysql"))) db, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } t.Logf("db: %#v", db) ctx := context.Background() batch := 512 tableName := "hetu_zeus_0" cols := []string{"group_id", "page_id", "fea_id", "entity_id", "feature0", "feature1", "extend_info"} query := fmt.Sprintf(`INSERT INTO %s ( group_id, page_id, fea_id, entity_id, feature0, feature1, extend_info ) VALUES %s `, tableName, mysql_.JoinNamedColumnsValuesBatch(cols, batch)) testCases := []struct { TableName string GroupId string Number int64 }{ { TableName: "hetu_zeus_0", GroupId: "hetu_image_copyright_prod", }, } for _, testCase := range testCases { t.Run(fmt.Sprintf("table[%v]-fieldKey[%v]", testCase.TableName, testCase.GroupId), func(t *testing.T) { count := batch var args []*TaskTable for count > 0 { arg := &TaskTable{ GroupId: testCase.GroupId, PageId: "100", FeaId: uuid.NewString(), EntityId: "200", Feature0: []byte("Feature0"), Feature1: []byte("Feature1"), ExtendInfo: []byte("ExtendInfo"), } args = append(args, arg) count-- } _, err = mysql_.ExecContext(ctx, query, mysql_.BuildNamedColumnsValuesBatch(args), nil, db) if err != nil { t.Errorf("faild to insert %v, err: %v", args, err) } }) } } func TestInsertBatch(t *testing.T) { cfgFile := "./mysql.dev.yaml" config := mysql_.NewConfig(mysql_.WithViper(viper_.GetViper(cfgFile, "database.mysql"))) db, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } t.Logf("db: %#v", db) ctx := context.Background() tableName := "hetu_zeus_0" query := fmt.Sprintf(`INSERT INTO %s ( group_id, page_id, fea_id, entity_id, feature0, feature1, extend_info ) VALUES ( :group_id_1, :page_id_1, :fea_id_1, :entity_id_1, :feature0_1, :feature1_1, :extend_info_1 ), ( :group_id_2, :page_id_2, :fea_id_2, :entity_id_2, :feature0_2, :feature1_2, :extend_info_2 ) `, tableName) testCases := []struct { TableName string GroupId string Number int64 }{ { TableName: "hetu_zeus_0", GroupId: "hetu_image_copyright_prod", Number: 2, }, } for _, testCase := range testCases { t.Run(fmt.Sprintf("table[%v]-fieldKey[%v]", testCase.TableName, testCase.GroupId), func(t *testing.T) { count := testCase.Number var args []TaskTable for count > 0 { arg := TaskTable{ GroupId: testCase.GroupId, PageId: "100", FeaId: uuid.NewString(), EntityId: "200", Feature0: []byte("Feature0"), Feature1: []byte("Feature1"), ExtendInfo: []byte("ExtendInfo"), } args = append(args, arg) count-- } tagsValues := map[string]interface{}{ "group_id_1": "group_id_1", "page_id_1": uuid.NewString(), "fea_id_1": uuid.NewString(), "entity_id_1": uuid.NewString(), "feature0_1": "feature0_1", "feature1_1": "feature1_1", "extend_info_1": "extend_info_1", "group_id_2": "group_id_2", "page_id_2": uuid.NewString(), "fea_id_2": uuid.NewString(), "entity_id_2": uuid.NewString(), "feature0_2": "feature0_2", "feature1_2": "feature1_2", "extend_info_2": "extend_info_2", } t.Logf("batch insert %v", tagsValues) //_, err = mysql_.ExecContext(ctx, query, tagsValues, nil, db) //_, err = mysql_.ExecContext(ctx, query, []interface{}{tagsValues[0], tagsValues[1]}, nil, db) _, err = mysql_.ExecContext(ctx, query, tagsValues, nil, db) if err != nil { t.Errorf("faild to insert %v, err: %v", tagsValues, err) } }) } } func TestDeleteBatch(t *testing.T) { cfgFile := "./mysql.yaml" config := mysql_.NewConfig(mysql_.WithViper(viper_.GetViper(cfgFile, "database.mysql"))) db, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } t.Logf("db: %#v", db) ctx := context.Background() testCases := []struct { TableName string GroupId string DeleteField string Batch int64 }{ { TableName: "hetu_zeus_0", DeleteField: "group_id", GroupId: "hetu_image_copyright_prod", Batch: 5, }, } for _, testCase := range testCases { t.Run(fmt.Sprintf("table[%v]-fieldKey[%v]", testCase.TableName, testCase.GroupId), func(t *testing.T) { var count int64 arg := &TaskTable{ GroupId: testCase.GroupId, } for { query := fmt.Sprintf( `DELETE FROM %s WHERE %s limit %v`, testCase.TableName, mysql_.ConditionWithEqualAnd(testCase.DeleteField), testCase.Batch, ) rows, err := mysql_.ExecContext(ctx, query, arg, nil, db) if err != nil { t.Fatalf("failed to delete %v, current deleted total number: %v, err: %v", arg.GroupId, count, err) } count += rows if rows == 0 { t.Logf("finished to delete %v, total number: %v", arg.GroupId, count) break } if count%testCase.Batch == 0 { t.Logf("delete number: %v ...", count) } } }) } } ================================================ FILE: pkg/database/mysql/mysql_options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql // A DBOption sets options. type DBOption interface { apply(*DB) } // EmptyDBUrlOption does not alter the DBuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyDBOption struct{} func (EmptyDBOption) apply(*DB) {} // DBOptionFunc wraps a function that modifies DB into an // implementation of the DBOption interface. type DBOptionFunc func(*DB) func (f DBOptionFunc) apply(do *DB) { f(do) } // sample code for option, default for nothing to change func _DBOptionWithDefault() DBOption { return DBOptionFunc(func(*DB) { // nothing to change }) } func (o *DB) ApplyOptions(options ...DBOption) *DB { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/database/mysql/mysql_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql_test import ( "context" "testing" "time" mysql_ "github.com/kaydxh/golang/pkg/database/mysql" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/stretchr/testify/assert" ) func TestGetDataBase(t *testing.T) { testCases := []struct { Address string DataName string UserName string Password string InterpolateParams bool }{ { Address: "127.0.0.1:3306", DataName: "sealet", UserName: "root", Password: "123456", InterpolateParams: true, }, } for _, testCase := range testCases { t.Run(testCase.Address+testCase.DataName, func(t *testing.T) { db := mysql_.NewDB(mysql_.DBConfig{ Address: testCase.Address, DataName: testCase.DataName, UserName: testCase.UserName, Password: testCase.Password, }, mysql_.WithInterpolateParams(testCase.InterpolateParams), ) sqlDB, err := db.GetDatabase() if err != nil { t.Fatalf("failed to get database: %v, got : %s", testCase.DataName, err) } assert.NotNil(t, sqlDB) }) } } func TestGetDatabaseUntil(t *testing.T) { testCases := []struct { Address string DataName string UserName string Password string DailTimeout time.Duration }{ { Address: "127.0.0.1:3306", DataName: "test", UserName: "root", Password: "123456", DailTimeout: 3 * time.Second, }, } for _, testCase := range testCases { t.Run(testCase.Address+testCase.DataName, func(t *testing.T) { db := mysql_.NewDB(mysql_.DBConfig{ Address: testCase.Address, DataName: testCase.DataName, UserName: testCase.UserName, Password: testCase.Password, }, mysql_.WithDialTimeout(testCase.DailTimeout)) sqlDB, err := db.GetDatabaseUntil(context.Background(), 5*time.Second, 20*time.Second) if err != nil { t.Fatalf("failed to get database: %v, got : %s", testCase.DataName, err) } assert.NotNil(t, sqlDB) }) } } func TestNew(t *testing.T) { cfgFile := "./mysql.yaml" config := mysql_.NewConfig(mysql_.WithViper(viper_.GetViper(cfgFile, "database.mysql"))) db, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } t.Logf("db: %#v", db) } func TestGetTheDBAndClose(t *testing.T) { testCases := []struct { Address string DataName string UserName string Password string }{ { Address: "127.0.0.1:3306", DataName: "test", UserName: "root", Password: "123456", }, } for _, testCase := range testCases { t.Run(testCase.Address+testCase.DataName, func(t *testing.T) { conf := mysql_.DBConfig{ Address: testCase.Address, DataName: testCase.DataName, UserName: testCase.UserName, Password: testCase.Password, } db := mysql_.NewDB(conf) sqlDB, err := db.GetDatabaseUntil(context.Background(), 5*time.Second, 20*time.Second) if err != nil { t.Fatalf("failed to get database: %v, got : %s", testCase.DataName, err) } assert.NotNil(t, sqlDB) theDB, err := mysql_.GetTheDB(conf) assert.Nil(t, err) assert.Equal(t, sqlDB, mysql_.GetDB()) t.Logf("GetDB got sqlDB: %v, expect %v", sqlDB, mysql_.GetDB()) t.Logf("GetTheDB got sqlDB: %v, expect %v", sqlDB, theDB) err = mysql_.CloseTheDB(conf) assert.Nil(t, err) err = mysql_.CloseDB() assert.Nil(t, err) }) } } ================================================ FILE: pkg/database/mysql/mysql_transaction.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql import ( "context" "database/sql" "fmt" "github.com/jmoiron/sqlx" "github.com/sirupsen/logrus" ) type TxDao struct { *sqlx.Tx } func (d *TxDao) Begin(ctx context.Context, db *sqlx.DB, opts *sql.TxOptions) error { if db == nil { return fmt.Errorf("unexpected err: db is nil") } tx, err := db.BeginTxx(ctx, opts) if err != nil { return err } d.Tx = tx return nil } func (d *TxDao) Commit() error { if d.Tx == nil { return fmt.Errorf("unexpected err: tx is nil") } err := d.Tx.Commit() if err != nil { return err } return nil } // Rollback ... func (d *TxDao) Rollback() error { if d.Tx == nil { return fmt.Errorf("unexpected err: tx is nil") } err := d.Tx.Rollback() if err != nil { return err } return nil } func TxPipelined(ctx context.Context, db *sqlx.DB, fn func(*sqlx.Tx) error) (err error) { var tx TxDao err = tx.Begin(ctx, db, nil) if err != nil { logrus.WithError(err).Errorf("failed to transaction begin") return err } defer func() { if err != nil { if txErr := tx.Rollback(); txErr != nil { logrus.WithError(err).Errorf("failed to rollback, err: %v", txErr) return } return } if err = tx.Commit(); err != nil { logrus.WithError(err).Errorf("failed to commit") return } }() return fn(tx.Tx) } ================================================ FILE: pkg/database/mysql/sql.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql import ( "fmt" "strings" "github.com/jmoiron/sqlx" reflect_ "github.com/kaydxh/golang/go/reflect" strings_ "github.com/kaydxh/golang/go/strings" ) const dbTag = "db" type SqlCompare string const ( SqlCompareEqual SqlCompare = "=" SqlCompareNotEqual SqlCompare = "!=" SqlCompareGreater SqlCompare = ">" SqlCompareLessThan SqlCompare = "<" SqlCompareGreatEqual SqlCompare = ">=" SqlCompareLessEqual SqlCompare = "<=" SqlCompareLike SqlCompare = "LIKE" SqlCompareIn SqlCompare = "IN" ) type SqlOperator string const ( SqlOperatorAnd SqlOperator = "AND" SqlOperatorOr SqlOperator = "OR" SqlOperatorNot SqlOperator = "NOT" ) // "foo=:foo AND bar=:bar" func NonzeroCondition(cmp SqlCompare, oper SqlOperator, arg interface{}) string { condFields := reflect_.NonzeroFieldTags(arg, dbTag) return fmt.Sprintf(" %s ", func() string { if len(condFields) == 0 { return "TRUE" } return fmt.Sprintf("%s", JoinNamedColumnsValuesWithOperator(cmp, oper, condFields...)) }()) } func NonzeroFields(arg interface{}) []string { return reflect_.NonzeroFieldTags(arg, dbTag) } func ConditionWithEqualAnd(condFields ...string) string { return JoinNamedColumnsValuesWithOperator(SqlCompareEqual, SqlOperatorAnd, condFields...) } // "ORDER BY create_time DESC, id DESC" func OrderCondition(orders map[string]bool) string { if len(orders) == 0 { return "" } return fmt.Sprintf(" ORDER BY %s", func() string { var msg string for k, v := range orders { msg += fmt.Sprintf("%s %s,", k, func() string { if v { return "DESC" } return "ASC" }()) } msg = strings.TrimRight(msg, ",") return msg }()) } func InCondition(cond string, values ...string) string { if cond == "" || len(values) == 0 { return "TRUE" } return fmt.Sprintf(`%s IN (%s)`, cond, func() string { var msg string for _, v := range values { msg += fmt.Sprintf(`"%s",`, v) } msg = strings.TrimRight(msg, ",") return msg }()) } func NamedInCondition(oper SqlOperator, cols []string, arg interface{}) (string, error) { query := JoinNamedColumnsValuesWithOperator(SqlCompareIn, oper, cols...) query, args, err := sqlx.Named(query, arg) if err != nil { return "", err } query, args, err = sqlx.In(query, args...) if err != nil { return "", err } return strings_.ReplaceAll(query, "?", args, true), nil } // JoinNamedColumnsValues foo=:foo,bar=:bar, for update set func JoinNamedColumnsValues(cols ...string) string { return strings.Join(namedTableColumnsValues(SqlCompareEqual, cols...), ",") } // JoinNamedColumnsValuesWithOperator "foo=:foo AND bar=:bar" , for where condition func JoinNamedColumnsValuesWithOperator(cmp SqlCompare, oper SqlOperator, cols ...string) string { conds := strings.Join(namedTableColumnsValues(cmp, cols...), fmt.Sprintf(" %s ", oper)) if len(cols) == 0 || conds == "" { return "TRUE" } return conds } // []string{"foo=:foo", "bar=:bar"} func namedTableColumnsValues(cmp SqlCompare, cols ...string) []string { var namedCols []string for _, col := range cols { if col != "" { switch cmp { case SqlCompareLike: namedCols = append(namedCols, fmt.Sprintf(`%[1]s %[2]s concat("%%",:%[1]s,"%%")`, col, cmp)) case SqlCompareIn: namedCols = append(namedCols, fmt.Sprintf("%[1]s %[2]s (:%[1]s)", col, cmp)) default: namedCols = append(namedCols, fmt.Sprintf("%[1]s %[2]s :%[1]s", col, cmp)) } } } return namedCols } /* used for batch insert ( :group_id_1, :page_id_1, :fea_id_1, :entity_id_1, :feature0_1, :feature1_1, :extend_info_1 ), ( :group_id_2, :page_id_2, :fea_id_2, :entity_id_2, :feature0_2, :feature1_2, :extend_info_2 ) */ func JoinNamedColumnsValuesBatch(cols []string, batch int) string { var batchNamedCols []string for i := 0; i < batch; i++ { var namedCols []string for _, col := range cols { namedCols = append(namedCols, fmt.Sprintf(":%s_%d", col, i)) } batchNamedCols = append(batchNamedCols, fmt.Sprintf("(%v)", strings.Join(namedCols, ","))) } return strings.Join(batchNamedCols, ",") } func BuildNamedInsertSql(table string, cols []string, batch int) string { if table == "" || len(cols) == 0 { return "" } sql := fmt.Sprintf(`INSERT INTO %s ( %s ) VALUES %s`, table, strings.Join(cols, ","), JoinNamedColumnsValuesBatch(cols, batch)) return sql } // used for batch insert func TransferToNamedColumnsValuesBatch(req []map[string]interface{}) map[string]interface{} { valuesMap := make(map[string]interface{}, 0) for i, values := range req { for k, v := range values { valuesMap[fmt.Sprintf("%s_%d", k, i)] = v } } return valuesMap } // req is slice of struct or pointer struct func BuildNamedColumnsValuesBatch(req interface{}) map[string]interface{} { return TransferToNamedColumnsValuesBatch(reflect_.ArrayAllTagsVaules(req, dbTag)) } ================================================ FILE: pkg/database/mysql/sql_exec.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql import ( "context" "database/sql" "fmt" runtime_ "github.com/kaydxh/golang/go/runtime" time_ "github.com/kaydxh/golang/go/time" "github.com/sirupsen/logrus" "github.com/jmoiron/sqlx" ) /* func ExecContext( ctx context.Context, timeout time.Duration, db *sqlx.DB, query string, h func(ctx context.Context, db *sqlx.DB, query string) error, ) error { if h == nil { return nil } ctx, cancel := context_.WithTimeout(ctx, timeout) defer cancel() return h(ctx, db, query) } */ func ExecContext( ctx context.Context, query string, arg interface{}, tx *sqlx.Tx, db *sqlx.DB, ) (rows int64, err error) { tc := time_.New(true) caller := runtime_.GetShortCaller() logger := logrus.WithField("caller", caller) clean := func() { tc.Tick(caller) logger.WithField("cost", tc.String()).Infof("SQL EXECL") if err != nil { logger.WithError(err).Errorf("sql: %s", query) } } defer clean() result, err := NamedExecContext(ctx, query, arg, tx, db) if err != nil { return 0, err } rows, err = result.RowsAffected() if err != nil { return 0, err } logger.Infof("affected rows: %v", rows) return rows, nil } // pointer struct model for dest func SelectNamedContext( ctx context.Context, query string, arg interface{}, dest interface{}, db *sqlx.DB, ) (err error) { tc := time_.New(true) caller := runtime_.GetShortCaller() logger := logrus.WithField("caller", caller) clean := func() { tc.Tick(caller) logger.WithField("cost", tc.String()).Infof("SQL EXECL") if err != nil { logger.WithError(err).Errorf("sql: %s", query) } } defer clean() // prepare ns, err := db.PrepareNamedContext(ctx, query) if err != nil { return err } defer ns.Close() // query return ns.SelectContext(ctx, dest, arg) } func GetCountContext(ctx context.Context, query string, arg interface{}, db *sqlx.DB) (count uint32, err error) { tc := time_.New(true) caller := runtime_.GetShortCaller() logger := logrus.WithField("caller", caller) clean := func() { tc.Tick(caller) logger.WithField("cost", tc.String()).Infof("SQL EXECL") if err != nil { logger.WithError(err).Errorf("sql: %s", query) } } defer clean() ns, err := db.PrepareNamedContext(ctx, query) if err != nil { return 0, err } defer ns.Close() err = ns.QueryRowContext(ctx, arg).Scan(&count) if err != nil { return 0, err } return count, nil } func NamedExecContext( ctx context.Context, query string, arg interface{}, tx *sqlx.Tx, db *sqlx.DB, ) (sql.Result, error) { if tx != nil { return tx.NamedExecContext(ctx, query, arg) } if db != nil { return db.NamedExecContext(ctx, query, arg) } return nil, fmt.Errorf("db is nil") } func PrepareNamedContext(ctx context.Context, query string, tx *sqlx.Tx, db *sqlx.DB, ) (*sqlx.NamedStmt, error) { if tx != nil { return tx.PrepareNamedContext(ctx, query) } if db != nil { return db.PrepareNamedContext(ctx, query) } return nil, fmt.Errorf("db is nil") } ================================================ FILE: pkg/database/mysql/sql_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql_test import ( "fmt" "testing" mysql_ "github.com/kaydxh/golang/pkg/database/mysql" ) func TestJoinNamedColumnsValuesWithOperator(t *testing.T) { testCases := []struct { cmp mysql_.SqlCompare oper mysql_.SqlOperator cols []string }{ { cmp: mysql_.SqlCompareLike, oper: mysql_.SqlOperatorAnd, cols: []string{"task_name"}, }, } for _, testCase := range testCases { t.Run(string(testCase.cmp), func(t *testing.T) { query := mysql_.JoinNamedColumnsValuesWithOperator(testCase.cmp, testCase.oper, testCase.cols...) t.Logf("sql: %v", query) }) } } func TestInCondition(t *testing.T) { testCases := []struct { cond string values []string }{ { cond: "task_id", values: []string{"task_id_1", "task_id_2"}, }, { cond: "task_id", values: []string{"", ""}, }, } for _, testCase := range testCases { t.Run(string(testCase.cond), func(t *testing.T) { query := mysql_.InCondition(testCase.cond, testCase.values...) t.Logf("sql: %v", query) }) } } func TestNamedInCondition(t *testing.T) { testCases := []struct { cols []string arg interface{} }{ { cols: []string{"task_id"}, arg: struct { TaskId []string `db:"task_id"` }{ TaskId: []string{"task_id_1", "task_id_2"}, }, }, { cols: []string{"task_id"}, arg: struct { TaskId []int `db:"task_id"` }{ TaskId: []int{0, 1}, }, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { query, err := mysql_.NamedInCondition(mysql_.SqlOperatorAnd, testCase.cols, testCase.arg) if err != nil { t.Fatalf("err: %v", err) } t.Logf("sql: %v", query) }) } } func TestOrderCondition(t *testing.T) { testCases := []struct { orders map[string]bool }{ { orders: map[string]bool{ "task_id": true, }, }, { orders: map[string]bool{ "task_id": false, "score": false, }, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { query := mysql_.OrderCondition(testCase.orders) t.Logf("sql: %v", query) }) } } func TestJoinNamedColumnsValuesBatch(t *testing.T) { testCases := []struct { cols []string batch int }{ { cols: []string{"task_name", "task_id", "task_arg"}, batch: 4, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("case-%v", i), func(t *testing.T) { query := mysql_.JoinNamedColumnsValuesBatch(testCase.cols, testCase.batch) t.Logf("sql: %v", query) }) } } /* func TestGenerateSQL(t *testing.T) { arg := struct { TaskId string `db:"task_id"` Name []string `db:"name"` }{ TaskId: "task-id", Name: []string{"name1", "name2"}, } //sql := "SELECT *FROM t_task where task_id=:task_id and name In(:name)" sql := "SELECT *FROM t_task where task_id=:task_id" query, args, err := sqlx.Named(sql, arg) if err != nil { t.Fatalf("falied to named, err: %v", err) } query, args, err = sqlx.In(query, args...) if err != nil { t.Fatalf("falied to In, err: %v", err) } // ns, err := d.db.PrepareNamedContext(ctx, query) t.Logf("query: %v, args: %v", query, args) } */ ================================================ FILE: pkg/database/mysql/sql_type.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 mysql import ( "sync/atomic" "github.com/jmoiron/sqlx" ) type SQLDB atomic.Value //check type SQLDB* whether to implement interface of atomic.Value //var _ atomic.Value = (*SQLDB)(nil) //check type SQLDB whether to implement interface of atomic.Value //var _ atomic.Value = SQLDB{} func (m *SQLDB) Store(value *sqlx.DB) { (*atomic.Value)(m).Store(value) } func (m *SQLDB) Load() *sqlx.DB { value := (*atomic.Value)(m).Load() if value == nil { return nil } return value.(*sqlx.DB) } ================================================ FILE: pkg/database/redis/command.get.values.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis import ( "context" "fmt" "github.com/go-redis/redis/v8" ) func GetValue(ctx context.Context, db *redis.Client, key string) ([]string, error) { if db == nil { return nil, fmt.Errorf("found unexpected nil redis client") } var values []string typ, err := db.Type(ctx, key).Result() if err != nil { return nil, fmt.Errorf("failed to get type of key: %v, err: %v", key, err) } switch typ { case "string": data, err := db.Get(ctx, key).Result() if err != nil { return nil, fmt.Errorf("failed to get value of key: %v, err: %v", key, err) } values = append(values, data) case "list": llen, err := db.LLen(ctx, key).Result() if err != nil { return nil, fmt.Errorf("failed to get len of key: %v, err: %v", key, err) } var i int64 for i = 0; i < llen; i++ { data, err := db.LIndex(ctx, key, i).Result() if err != nil { return nil, fmt.Errorf("failed to get list data of key: %v, err: %v", key, err) } values = append(values, data) } case "set": members, err := db.SMembers(ctx, key).Result() if err != nil { return nil, fmt.Errorf("failed to get members of key: %v, err: %v", key, err) } values = append(values, members...) default: } return values, nil } func GetValues(ctx context.Context, db *redis.Client, keys ...string) ([][]string, error) { if db == nil { return nil, fmt.Errorf("found unexpected nil redis client") } var values [][]string for _, key := range keys { value, err := GetValue(ctx, db, key) if err != nil { return nil, err } values = append(values, value) } return values, nil } ================================================ FILE: pkg/database/redis/command.hset.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis import ( "context" "fmt" "github.com/go-redis/redis/v8" reflect_ "github.com/kaydxh/golang/go/reflect" ) // only get export Fields from arg // set tag-values for field-value to hash func HSetStruct(ctx context.Context, db *redis.Client, key string, arg interface{}) error { if db == nil { return fmt.Errorf("found unexpected nil redis client") } tagsValues := reflect_.AllTagsValues(arg, "redis") _, err := db.HSet(ctx, key, tagsValues).Result() if err != nil { return fmt.Errorf("failed to HSet key: %v, err: %v", key, err) } return nil } ================================================ FILE: pkg/database/redis/config.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis import ( "context" "github.com/go-redis/redis/v8" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) type Config struct { Proto Redis opts struct { // If set, overrides params below viper *viper.Viper } } type completedConfig struct { *Config completeError error } type CompletedConfig struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig } func (c *completedConfig) New(ctx context.Context) (*redis.Client, error) { logrus.Infof("Installing Redis") if c.completeError != nil { return nil, c.completeError } if !c.Proto.GetEnabled() { logrus.Warnf("Redis disenabled") return nil, nil } redisDB, err := c.install(ctx) if err != nil { return nil, err } logrus.Infof("Installed Redis") return redisDB, nil } func (c *completedConfig) install(ctx context.Context) (*redis.Client, error) { db := NewRedisClient( DBConfig{ Addresses: c.Proto.GetAddresses(), UserName: c.Proto.GetUsername(), Password: c.Proto.GetPassword(), DB: int(c.Proto.GetDb()), }, WithPoolSize(int(c.Proto.GetPoolSize())), WithMinIdleConnections(int(c.Proto.GetMinIdleConns())), WithDialTimeout(c.Proto.GetDialTimeout().AsDuration()), WithReadTimeout(c.Proto.GetReadTimeout().AsDuration()), WithWriteTimeout(c.Proto.GetWriteTimeout().AsDuration()), ) return db.GetDatabaseUntil( ctx, c.Proto.GetMaxWaitDuration().AsDuration(), c.Proto.GetFailAfterDuration().AsDuration(), ) } // Complete set default ServerRunOptions. func (c *Config) Complete() CompletedConfig { err := c.loadViper() if err != nil { return CompletedConfig{&completedConfig{ Config: c, completeError: err, }} } return CompletedConfig{&completedConfig{Config: c}} } func (c *Config) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, &c.Proto) } return nil } func NewConfig(options ...ConfigOption) *Config { c := &Config{} c.ApplyOptions(options...) return c } ================================================ FILE: pkg/database/redis/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis import ( "github.com/spf13/viper" ) func WithViper(v *viper.Viper) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.viper = v }) } ================================================ FILE: pkg/database/redis/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis // A ConfigOption sets options. type ConfigOption interface { apply(*Config) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption struct{} func (EmptyConfigOption) apply(*Config) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc func(*Config) func (f ConfigOptionFunc) apply(do *Config) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault() ConfigOption { return ConfigOptionFunc(func(*Config) { // nothing to change }) } func (o *Config) ApplyOptions(options ...ConfigOption) *Config { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/database/redis/redis.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis import ( "context" "fmt" "time" "github.com/go-redis/redis/v8" time_ "github.com/kaydxh/golang/go/time" ) var redisDB RedisDB // Default values for Redis. const ( DefaultMinIdleConns = 10 DefaultPoolSize = 10 DefaultDialTimeout = 5 * time.Second DefaultReadTimeout = 5 * time.Second DefaultWriteTimeout = 5 * time.Second DefaultMasterName = "mymaster" ) type DBConfig struct { Addresses []string UserName string Password string DB int } type RedisClient struct { Conf DBConfig db *redis.Client opts struct { poolSize int minIdleConns int dialTimeout time.Duration readTimeout time.Duration writeTimeout time.Duration masterName string } } func NewRedisClient(conf DBConfig, opts ...RedisOption) *RedisClient { c := &RedisClient{ Conf: conf, } c.opts.poolSize = DefaultPoolSize c.opts.minIdleConns = DefaultMinIdleConns c.opts.dialTimeout = DefaultDialTimeout c.opts.readTimeout = DefaultReadTimeout c.opts.writeTimeout = DefaultWriteTimeout c.opts.masterName = DefaultMasterName c.ApplyOptions(opts...) return c } func GetDB() *redis.Client { return redisDB.Load() } func (r *RedisClient) GetRedis(ctx context.Context) (*redis.Client, error) { if r.db != nil { return r.db, nil } if len(r.Conf.Addresses) == 0 { return nil, fmt.Errorf("invalid redis address") } var db *redis.Client if len(r.Conf.Addresses) == 1 { db = redis.NewClient(&redis.Options{ Addr: r.Conf.Addresses[0], Password: r.Conf.Password, DB: r.Conf.DB, PoolSize: r.opts.poolSize, MinIdleConns: r.opts.minIdleConns, DialTimeout: r.opts.dialTimeout, ReadTimeout: r.opts.readTimeout, WriteTimeout: r.opts.writeTimeout, }) } if len(r.Conf.Addresses) > 1 { db = redis.NewFailoverClient(&redis.FailoverOptions{ MasterName: r.opts.masterName, SentinelAddrs: r.Conf.Addresses, Password: r.Conf.Password, DB: r.Conf.DB, PoolSize: r.opts.poolSize, MinIdleConns: r.opts.minIdleConns, DialTimeout: r.opts.dialTimeout, ReadTimeout: r.opts.readTimeout, WriteTimeout: r.opts.writeTimeout, }) } _, err := db.Ping(ctx).Result() if err != nil { return nil, err } r.db = db redisDB.Store(db) return r.db, nil } func (r *RedisClient) GetDatabaseUntil( ctx context.Context, maxWaitInterval time.Duration, failAfter time.Duration) (*redis.Client, error) { var db *redis.Client exp := time_.NewExponentialBackOff( time_.WithExponentialBackOffOptionMaxInterval(maxWaitInterval), time_.WithExponentialBackOffOptionMaxElapsedTime(failAfter), ) err := time_.BackOffUntilWithContext(ctx, func(ctx context.Context) (err_ error) { db, err_ = r.GetRedis(ctx) if err_ != nil { return err_ } return nil }, exp, true, false) if err != nil { return nil, fmt.Errorf("get database fail after: %v", failAfter) } return db, nil } func (r *RedisClient) Close() error { if r.db == nil { return fmt.Errorf("no redis client") } return r.db.Close() } ================================================ FILE: pkg/database/redis/redis.options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis import "time" func WithPoolSize(poolSize int) RedisOption { return RedisOptionFunc(func(c *RedisClient) { c.opts.poolSize = poolSize }) } func WithMinIdleConnections(minIdleConns int) RedisOption { return RedisOptionFunc(func(c *RedisClient) { c.opts.minIdleConns = minIdleConns }) } func WithDialTimeout(dialTimeout time.Duration) RedisOption { return RedisOptionFunc(func(c *RedisClient) { c.opts.dialTimeout = dialTimeout }) } func WithReadTimeout(readTimeout time.Duration) RedisOption { return RedisOptionFunc(func(c *RedisClient) { c.opts.readTimeout = readTimeout }) } func WithWriteTimeout(writeTimeout time.Duration) RedisOption { return RedisOptionFunc(func(c *RedisClient) { c.opts.writeTimeout = writeTimeout }) } func WithMasterName(masterName string) RedisOption { return RedisOptionFunc(func(c *RedisClient) { c.opts.masterName = masterName }) } ================================================ FILE: pkg/database/redis/redis.pb.go ================================================ /* *Copyright (c) 2022, kaydxh * *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. */ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 // protoc v3.13.0 // source: pkg/database/redis/redis.proto package redis import ( duration "github.com/golang/protobuf/ptypes/duration" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // https://github.com/go-redis/redis/blob/ce40cd942a72c4a93f9025047e6fd3f510700ab3/options.go type Redis struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` // Either a single address or a seed list of host:port addresses // of cluster/sentinel nodes. Addresses []string `protobuf:"bytes,2,rep,name=addresses,proto3" json:"addresses,omitempty"` // Database to be selected after connecting to the server. // Only single-node and failover clients. Db int64 `protobuf:"varint,3,opt,name=db,proto3" json:"db,omitempty"` // Use the specified Username to authenticate the current connection // with one of the connections defined in the ACL list when connecting // to a Redis 6.0 instance, or greater, that is using the Redis ACL system. Username string `protobuf:"bytes,4,opt,name=username,proto3" json:"username,omitempty"` // Optional password. Must match the password specified in the // requirepass server configuration option (if connecting to a Redis 5.0 // instance, or lower), or the User Password when connecting to a Redis 6.0 // instance, or greater, that is using the Redis ACL system. Password string `protobuf:"bytes,5,opt,name=password,proto3" json:"password,omitempty"` // Maximumumber of retries before giving up. // Default is 3 retries. MaxRetries int64 `protobuf:"varint,7,opt,name=max_retries,json=maxRetries,proto3" json:"max_retries,omitempty"` // Minimum backoff between each retry. // Default is 8 milliseconds; -1 disables backoff. MinRetryBackoff *duration.Duration `protobuf:"bytes,8,opt,name=min_retry_backoff,json=minRetryBackoff,proto3" json:"min_retry_backoff,omitempty"` // Maximum backoff between each retry. // Default is 512 milliseconds; -1 disables backoff. MaxRetryBackoff *duration.Duration `protobuf:"bytes,9,opt,name=max_retry_backoff,json=maxRetryBackoff,proto3" json:"max_retry_backoff,omitempty"` // Dial timeout for establishing new connections. // Default is 5 seconds. DialTimeout *duration.Duration `protobuf:"bytes,10,opt,name=dial_timeout,json=dialTimeout,proto3" json:"dial_timeout,omitempty"` // Timeout for socket reads. If reached, commands will fail // with a timeout instead of blocking. Use value -1 for no timeout and 0 for // default. Default is 3 seconds. ReadTimeout *duration.Duration `protobuf:"bytes,11,opt,name=read_timeout,json=readTimeout,proto3" json:"read_timeout,omitempty"` // Timeout for socket writes. If reached, commands will fail // with a timeout instead of blocking. // Default is ReadTimeout. WriteTimeout *duration.Duration `protobuf:"bytes,12,opt,name=write_timeout,json=writeTimeout,proto3" json:"write_timeout,omitempty"` // Maximum number of socket connections. // Default is 10 connections per every available CPU as reported by // runtime.GOMAXPROCS. PoolSize int64 `protobuf:"varint,13,opt,name=pool_size,json=poolSize,proto3" json:"pool_size,omitempty"` // Minimum number of idle connections which is useful when establishing // new connection is slow. MinIdleConns int64 `protobuf:"varint,14,opt,name=min_idle_conns,json=minIdleConns,proto3" json:"min_idle_conns,omitempty"` // Connection age at which client retires (closes) the connection. // Default is to not close aged connections. MaxConnAge *duration.Duration `protobuf:"bytes,15,opt,name=max_conn_age,json=maxConnAge,proto3" json:"max_conn_age,omitempty"` // Amount of time client waits for connection if all connections // are busy before returning an error. // Default is ReadTimeout + 1 second. PoolTimeout *duration.Duration `protobuf:"bytes,16,opt,name=pool_timeout,json=poolTimeout,proto3" json:"pool_timeout,omitempty"` // Amount of time after which client closes idle connections. // Should be less than server's timeout. // Default is 5 minutes. -1 disables idle timeout check. IdleTimeout *duration.Duration `protobuf:"bytes,17,opt,name=idle_timeout,json=idleTimeout,proto3" json:"idle_timeout,omitempty"` // Frequency of idle checks made by idle connections reaper. // Default is 1 minute. -1 disables idle connections reaper, // but idle connections are still discarded by the client // if IdleTimeout is set. IdleCheckFrequency *duration.Duration `protobuf:"bytes,18,opt,name=idle_check_frequency,json=idleCheckFrequency,proto3" json:"idle_check_frequency,omitempty"` // Only cluster clients. MaxRedirects int64 `protobuf:"varint,19,opt,name=max_redirects,json=maxRedirects,proto3" json:"max_redirects,omitempty"` ReadOnly bool `protobuf:"varint,20,opt,name=read_only,json=readOnly,proto3" json:"read_only,omitempty"` // Allows routing read-only commands to the closest master or slave node. // This option only works with NewFailoverClusterClient. RouteByLatency bool `protobuf:"varint,21,opt,name=route_by_latency,json=routeByLatency,proto3" json:"route_by_latency,omitempty"` // Allows routing read-only commands to the random master or slave node. // This option only works with NewFailoverClusterClient. RouteRandomly bool `protobuf:"varint,22,opt,name=route_randomly,json=routeRandomly,proto3" json:"route_randomly,omitempty"` // Route all commands to slave read-only nodes. // The sentinel master name. // Only failover clients. // The master name. MasterName string `protobuf:"bytes,23,opt,name=master_name,json=masterName,proto3" json:"master_name,omitempty"` MaxWaitDuration *duration.Duration `protobuf:"bytes,24,opt,name=max_wait_duration,json=maxWaitDuration,proto3" json:"max_wait_duration,omitempty"` FailAfterDuration *duration.Duration `protobuf:"bytes,25,opt,name=fail_after_duration,json=failAfterDuration,proto3" json:"fail_after_duration,omitempty"` } func (x *Redis) Reset() { *x = Redis{} if protoimpl.UnsafeEnabled { mi := &file_pkg_database_redis_redis_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Redis) String() string { return protoimpl.X.MessageStringOf(x) } func (*Redis) ProtoMessage() {} func (x *Redis) ProtoReflect() protoreflect.Message { mi := &file_pkg_database_redis_redis_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Redis.ProtoReflect.Descriptor instead. func (*Redis) Descriptor() ([]byte, []int) { return file_pkg_database_redis_redis_proto_rawDescGZIP(), []int{0} } func (x *Redis) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *Redis) GetAddresses() []string { if x != nil { return x.Addresses } return nil } func (x *Redis) GetDb() int64 { if x != nil { return x.Db } return 0 } func (x *Redis) GetUsername() string { if x != nil { return x.Username } return "" } func (x *Redis) GetPassword() string { if x != nil { return x.Password } return "" } func (x *Redis) GetMaxRetries() int64 { if x != nil { return x.MaxRetries } return 0 } func (x *Redis) GetMinRetryBackoff() *duration.Duration { if x != nil { return x.MinRetryBackoff } return nil } func (x *Redis) GetMaxRetryBackoff() *duration.Duration { if x != nil { return x.MaxRetryBackoff } return nil } func (x *Redis) GetDialTimeout() *duration.Duration { if x != nil { return x.DialTimeout } return nil } func (x *Redis) GetReadTimeout() *duration.Duration { if x != nil { return x.ReadTimeout } return nil } func (x *Redis) GetWriteTimeout() *duration.Duration { if x != nil { return x.WriteTimeout } return nil } func (x *Redis) GetPoolSize() int64 { if x != nil { return x.PoolSize } return 0 } func (x *Redis) GetMinIdleConns() int64 { if x != nil { return x.MinIdleConns } return 0 } func (x *Redis) GetMaxConnAge() *duration.Duration { if x != nil { return x.MaxConnAge } return nil } func (x *Redis) GetPoolTimeout() *duration.Duration { if x != nil { return x.PoolTimeout } return nil } func (x *Redis) GetIdleTimeout() *duration.Duration { if x != nil { return x.IdleTimeout } return nil } func (x *Redis) GetIdleCheckFrequency() *duration.Duration { if x != nil { return x.IdleCheckFrequency } return nil } func (x *Redis) GetMaxRedirects() int64 { if x != nil { return x.MaxRedirects } return 0 } func (x *Redis) GetReadOnly() bool { if x != nil { return x.ReadOnly } return false } func (x *Redis) GetRouteByLatency() bool { if x != nil { return x.RouteByLatency } return false } func (x *Redis) GetRouteRandomly() bool { if x != nil { return x.RouteRandomly } return false } func (x *Redis) GetMasterName() string { if x != nil { return x.MasterName } return "" } func (x *Redis) GetMaxWaitDuration() *duration.Duration { if x != nil { return x.MaxWaitDuration } return nil } func (x *Redis) GetFailAfterDuration() *duration.Duration { if x != nil { return x.FailAfterDuration } return nil } var File_pkg_database_redis_redis_proto protoreflect.FileDescriptor var file_pkg_database_redis_redis_proto_rawDesc = []byte{ 0x0a, 0x1e, 0x70, 0x6b, 0x67, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x72, 0x65, 0x64, 0x69, 0x73, 0x2f, 0x72, 0x65, 0x64, 0x69, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x72, 0x65, 0x64, 0x69, 0x73, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x81, 0x09, 0x0a, 0x05, 0x52, 0x65, 0x64, 0x69, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x12, 0x0e, 0x0a, 0x02, 0x64, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x64, 0x62, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x6d, 0x61, 0x78, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x6d, 0x61, 0x78, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x73, 0x12, 0x45, 0x0a, 0x11, 0x6d, 0x69, 0x6e, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x79, 0x5f, 0x62, 0x61, 0x63, 0x6b, 0x6f, 0x66, 0x66, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x6d, 0x69, 0x6e, 0x52, 0x65, 0x74, 0x72, 0x79, 0x42, 0x61, 0x63, 0x6b, 0x6f, 0x66, 0x66, 0x12, 0x45, 0x0a, 0x11, 0x6d, 0x61, 0x78, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x79, 0x5f, 0x62, 0x61, 0x63, 0x6b, 0x6f, 0x66, 0x66, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x6d, 0x61, 0x78, 0x52, 0x65, 0x74, 0x72, 0x79, 0x42, 0x61, 0x63, 0x6b, 0x6f, 0x66, 0x66, 0x12, 0x3c, 0x0a, 0x0c, 0x64, 0x69, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x3c, 0x0a, 0x0c, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x72, 0x65, 0x61, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x3e, 0x0a, 0x0d, 0x77, 0x72, 0x69, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x77, 0x72, 0x69, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x6f, 0x6f, 0x6c, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x70, 0x6f, 0x6f, 0x6c, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x24, 0x0a, 0x0e, 0x6d, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x6c, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x73, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x6d, 0x69, 0x6e, 0x49, 0x64, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x73, 0x12, 0x3b, 0x0a, 0x0c, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x5f, 0x61, 0x67, 0x65, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0a, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x6e, 0x41, 0x67, 0x65, 0x12, 0x3c, 0x0a, 0x0c, 0x70, 0x6f, 0x6f, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x10, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x70, 0x6f, 0x6f, 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x3c, 0x0a, 0x0c, 0x69, 0x64, 0x6c, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x69, 0x64, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x4b, 0x0a, 0x14, 0x69, 0x64, 0x6c, 0x65, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x5f, 0x66, 0x72, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x79, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x12, 0x69, 0x64, 0x6c, 0x65, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x46, 0x72, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x79, 0x12, 0x23, 0x0a, 0x0d, 0x6d, 0x61, 0x78, 0x5f, 0x72, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x73, 0x18, 0x13, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x52, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x18, 0x14, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4f, 0x6e, 0x6c, 0x79, 0x12, 0x28, 0x0a, 0x10, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x5f, 0x62, 0x79, 0x5f, 0x6c, 0x61, 0x74, 0x65, 0x6e, 0x63, 0x79, 0x18, 0x15, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x42, 0x79, 0x4c, 0x61, 0x74, 0x65, 0x6e, 0x63, 0x79, 0x12, 0x25, 0x0a, 0x0e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x5f, 0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x6c, 0x79, 0x18, 0x16, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x6c, 0x79, 0x12, 0x1f, 0x0a, 0x0b, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x17, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x45, 0x0a, 0x11, 0x6d, 0x61, 0x78, 0x5f, 0x77, 0x61, 0x69, 0x74, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x18, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x6d, 0x61, 0x78, 0x57, 0x61, 0x69, 0x74, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x49, 0x0a, 0x13, 0x66, 0x61, 0x69, 0x6c, 0x5f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x19, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x11, 0x66, 0x61, 0x69, 0x6c, 0x41, 0x66, 0x74, 0x65, 0x72, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x33, 0x5a, 0x31, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x72, 0x65, 0x64, 0x69, 0x73, 0x3b, 0x72, 0x65, 0x64, 0x69, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_pkg_database_redis_redis_proto_rawDescOnce sync.Once file_pkg_database_redis_redis_proto_rawDescData = file_pkg_database_redis_redis_proto_rawDesc ) func file_pkg_database_redis_redis_proto_rawDescGZIP() []byte { file_pkg_database_redis_redis_proto_rawDescOnce.Do(func() { file_pkg_database_redis_redis_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_database_redis_redis_proto_rawDescData) }) return file_pkg_database_redis_redis_proto_rawDescData } var file_pkg_database_redis_redis_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_pkg_database_redis_redis_proto_goTypes = []interface{}{ (*Redis)(nil), // 0: go.pkg.database.redis.Redis (*duration.Duration)(nil), // 1: google.protobuf.Duration } var file_pkg_database_redis_redis_proto_depIdxs = []int32{ 1, // 0: go.pkg.database.redis.Redis.min_retry_backoff:type_name -> google.protobuf.Duration 1, // 1: go.pkg.database.redis.Redis.max_retry_backoff:type_name -> google.protobuf.Duration 1, // 2: go.pkg.database.redis.Redis.dial_timeout:type_name -> google.protobuf.Duration 1, // 3: go.pkg.database.redis.Redis.read_timeout:type_name -> google.protobuf.Duration 1, // 4: go.pkg.database.redis.Redis.write_timeout:type_name -> google.protobuf.Duration 1, // 5: go.pkg.database.redis.Redis.max_conn_age:type_name -> google.protobuf.Duration 1, // 6: go.pkg.database.redis.Redis.pool_timeout:type_name -> google.protobuf.Duration 1, // 7: go.pkg.database.redis.Redis.idle_timeout:type_name -> google.protobuf.Duration 1, // 8: go.pkg.database.redis.Redis.idle_check_frequency:type_name -> google.protobuf.Duration 1, // 9: go.pkg.database.redis.Redis.max_wait_duration:type_name -> google.protobuf.Duration 1, // 10: go.pkg.database.redis.Redis.fail_after_duration:type_name -> google.protobuf.Duration 11, // [11:11] is the sub-list for method output_type 11, // [11:11] is the sub-list for method input_type 11, // [11:11] is the sub-list for extension type_name 11, // [11:11] is the sub-list for extension extendee 0, // [0:11] is the sub-list for field type_name } func init() { file_pkg_database_redis_redis_proto_init() } func file_pkg_database_redis_redis_proto_init() { if File_pkg_database_redis_redis_proto != nil { return } if !protoimpl.UnsafeEnabled { file_pkg_database_redis_redis_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Redis); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_pkg_database_redis_redis_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_pkg_database_redis_redis_proto_goTypes, DependencyIndexes: file_pkg_database_redis_redis_proto_depIdxs, MessageInfos: file_pkg_database_redis_redis_proto_msgTypes, }.Build() File_pkg_database_redis_redis_proto = out.File file_pkg_database_redis_redis_proto_rawDesc = nil file_pkg_database_redis_redis_proto_goTypes = nil file_pkg_database_redis_redis_proto_depIdxs = nil } ================================================ FILE: pkg/database/redis/redis.proto ================================================ syntax = "proto3"; package go.pkg.database.redis; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/golang/pkg/database/redis;redis"; // https://github.com/go-redis/redis/blob/ce40cd942a72c4a93f9025047e6fd3f510700ab3/options.go message Redis { bool enabled = 1; // Either a single address or a seed list of host:port addresses // of cluster/sentinel nodes. repeated string addresses = 2; // Database to be selected after connecting to the server. // Only single-node and failover clients. int64 db = 3; // Use the specified Username to authenticate the current connection // with one of the connections defined in the ACL list when connecting // to a Redis 6.0 instance, or greater, that is using the Redis ACL system. string username = 4; // Optional password. Must match the password specified in the // requirepass server configuration option (if connecting to a Redis 5.0 // instance, or lower), or the User Password when connecting to a Redis 6.0 // instance, or greater, that is using the Redis ACL system. string password = 5; // Maximumumber of retries before giving up. // Default is 3 retries. int64 max_retries = 7; // Minimum backoff between each retry. // Default is 8 milliseconds; -1 disables backoff. google.protobuf.Duration min_retry_backoff = 8; // Maximum backoff between each retry. // Default is 512 milliseconds; -1 disables backoff. google.protobuf.Duration max_retry_backoff = 9; // Dial timeout for establishing new connections. // Default is 5 seconds. google.protobuf.Duration dial_timeout = 10; // Timeout for socket reads. If reached, commands will fail // with a timeout instead of blocking. Use value -1 for no timeout and 0 for // default. Default is 3 seconds. google.protobuf.Duration read_timeout = 11; // Timeout for socket writes. If reached, commands will fail // with a timeout instead of blocking. // Default is ReadTimeout. google.protobuf.Duration write_timeout = 12; // Maximum number of socket connections. // Default is 10 connections per every available CPU as reported by // runtime.GOMAXPROCS. int64 pool_size = 13; // Minimum number of idle connections which is useful when establishing // new connection is slow. int64 min_idle_conns = 14; // Connection age at which client retires (closes) the connection. // Default is to not close aged connections. google.protobuf.Duration max_conn_age = 15; // Amount of time client waits for connection if all connections // are busy before returning an error. // Default is ReadTimeout + 1 second. google.protobuf.Duration pool_timeout = 16; // Amount of time after which client closes idle connections. // Should be less than server's timeout. // Default is 5 minutes. -1 disables idle timeout check. google.protobuf.Duration idle_timeout = 17; // Frequency of idle checks made by idle connections reaper. // Default is 1 minute. -1 disables idle connections reaper, // but idle connections are still discarded by the client // if IdleTimeout is set. google.protobuf.Duration idle_check_frequency = 18; // Only cluster clients. int64 max_redirects = 19; bool read_only = 20; // Allows routing read-only commands to the closest master or slave node. // This option only works with NewFailoverClusterClient. bool route_by_latency = 21; // Allows routing read-only commands to the random master or slave node. // This option only works with NewFailoverClusterClient. bool route_randomly = 22; // Route all commands to slave read-only nodes. // The sentinel master name. // Only failover clients. // The master name. string master_name = 23; google.protobuf.Duration max_wait_duration = 24; google.protobuf.Duration fail_after_duration = 25; } ================================================ FILE: pkg/database/redis/redis.yaml ================================================ database: redis: enabled: true addresses: - "localhost:6379" password: "123456" db: 0 max_connections: 100 max_idle_connections: 10 dial_timeout: 5s max_wait_duration: 20s fail_after_duration: 60s ================================================ FILE: pkg/database/redis/redis_benchmark_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis_test import ( "context" "fmt" "testing" "time" "github.com/google/uuid" ) // -count the benchmark times, -benchtime the test execute times(用例执行次数) or execute time(用例执行时间) // -v detail log info , -benchmem summary of memory //go test -bench="Set" -benchtime=5s -count=3 . //go test -bench="Set" -benchtime=50x -count=3 . func BenchmarkSet(t *testing.B) { db := GetDBOrDie() // defer db.Close() keyPrefix := "test" for n := 0; n < t.N; n++ { fmt.Println("n: ", n) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() key := fmt.Sprintf("%s-%d", keyPrefix, n) result, err := db.Set(ctx, key, key, 0).Result() if err != nil { t.Fatalf("failed to set string, err: %v", err) } t.Logf("result of %v: %v", key, result) } } //go test -v -run=redis_benchmark_test.go -test.bench="ParallelSet" -benchtime=5s -count=3 . //go test -v -run=redis_benchmark_test.go -test.bench="ParallelSet" -benchtime=5s -count=3 . func BenchmarkParallelSet(t *testing.B) { db := GetDBOrDie() // defer db.Close() keyPrefix := "test" t.RunParallel(func(pb *testing.PB) { for pb.Next() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() key := fmt.Sprintf("%s-%s", keyPrefix, uuid.New().String()) result, err := db.Set(ctx, key, key, 0).Result() if err != nil { t.Fatalf("failed to set string, err: %v", err) } t.Logf("result of %v: %v", key, result) } }) } ================================================ FILE: pkg/database/redis/redis_hset_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis_test import ( "context" "testing" "time" redis_ "github.com/kaydxh/golang/pkg/database/redis" ) func TestHSetStruct(t *testing.T) { db := GetDBOrDie() // only get export Fields from testCases testCases := []struct { Key string `redis:"reids_key"` ID int64 `redis:"redis_id"` }{ { Key: "hset-test-1", ID: 1, }, { Key: "hset-test-2", ID: 2, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { err := redis_.HSetStruct(ctx, db, testCase.Key, testCase) if err != nil { t.Fatalf("failed to hset, err: %v", err) } t.Logf("key: %v, value: %v", testCase.Key, testCase) } } //get all fields by hash key func TestHKeys(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "hset-test-1", }, { Key: "hset-test-2", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { result, err := db.HKeys(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to HKeys, err: %v", err) } t.Logf("key: %v, result: %v", testCase.Key, result) } } //get all field-value by hash key func TestHGetAll(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "hset-test-1", }, { Key: "hset-test-2", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { result, err := db.HGetAll(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to hGetAll, err: %v", err) } t.Logf("key: %v, result: %v", testCase.Key, result) } } //get value by hash key and field func TestHGet(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Field string }{ { Key: "hset-test-1", Field: "redis_id", }, { Key: "hset-test-2", Field: "redis_id", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { fieldValues, err := db.HGet(ctx, testCase.Key, testCase.Field).Result() if err != nil { t.Fatalf("failed to hGet, err: %v", err) } t.Logf("key: %v, field: %v, result: %v", testCase.Key, testCase.Field, fieldValues) } } //exist hash key and field func TestHExists(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Field string }{ { Key: "hset-test-1", Field: "redis_id", }, { Key: "hset-test-2", Field: "redis_id", }, { Key: "hset-test-no-exist", Field: "redis_id", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { ok, err := db.HExists(ctx, testCase.Key, testCase.Field).Result() if err != nil { t.Fatalf("failed to hGet, err: %v", err) } t.Logf("key: %v, field: %v, result: %v", testCase.Key, testCase.Field, ok) } } // increment by hash key and field func TestHIncrBy(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Field string Incr int64 }{ { Key: "hset-test-1", Field: "redis_id", Incr: 1, }, { Key: "hset-test-2", Field: "redis_id", Incr: 2, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { // val is the result after incr val, err := db.HIncrBy(ctx, testCase.Key, testCase.Field, testCase.Incr).Result() if err != nil { t.Fatalf("failed to HIncrBy, err: %v", err) } t.Logf("key: %v, field: %v, val: %v", testCase.Key, testCase.Field, val) } } // get fields num by hash key func TestHLen(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "hset-test-1", }, { Key: "hset-test-2", }, { Key: "hset-test-no-exist", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { // count is the number of field by hash key count, err := db.HLen(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to HLen, err: %v", err) } t.Logf("key: %v, field count: %v", testCase.Key, count) } } // get values by fields and hash key func TestHMGet(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Field string }{ { Key: "hset-test-1", Field: "redis_id", }, { Key: "hset-test-2", Field: "redis_id", }, { Key: "hset-test-no-exist", Field: "redis_id", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { // vals is value of field by hash key vals, err := db.HMGet(ctx, testCase.Key, testCase.Field).Result() if err != nil { t.Fatalf("failed to HMGet, err: %v", err) } t.Logf("key: %v, field: %v, vals: %v", testCase.Key, testCase.Field, vals) } } // set values by fields and hash key func TestHMSet(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Field string Value interface{} }{ { Key: "hset-test-1", Field: "redis_id", Value: 10, }, { Key: "hset-test-2", Field: "redis_id", Value: 20, }, { Key: "hset-test-2", Field: "redis_id_new", Value: "new field", }, { Key: "hset-test-no-exist", Field: "redis_id", Value: 30, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { // count is the number of field by hash key ok, err := db.HMSet(ctx, testCase.Key, testCase.Field, testCase.Value).Result() if err != nil { t.Fatalf("failed to HMSet, err: %v", err) } t.Logf("key: %v, field: %v, ok: %v", testCase.Key, testCase.Field, ok) } } // set values by fields and hash key when field is not exist func TestHSetNX(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Field string Value interface{} }{ { Key: "hset-test-1", Field: "redis_id", Value: 10, }, { Key: "hset-test-2", Field: "redis_id", Value: 20, }, { Key: "hset-test-2", Field: "redis_id_new_1", Value: "new field_1", }, { Key: "hset-test-no-exist-1", Field: "redis_id", Value: 30, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { // count is the number of field by hash key ok, err := db.HSetNX(ctx, testCase.Key, testCase.Field, testCase.Value).Result() if err != nil { t.Fatalf("failed to HSetNX, err: %v", err) } t.Logf("key: %v, field: %v, ok: %v", testCase.Key, testCase.Field, ok) } } // set values by fields and hash key when field is not exist /* redis_hset_test.go:397: key: hset-test-1, values: [10 hset-test-1] redis_hset_test.go:397: key: hset-test-2, values: [hset-test-2 20 new field new field_1] redis_hset_test.go:397: key: hset-test-no-exist-1, values: [30] */ func TestHVals(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "hset-test-1", }, { Key: "hset-test-2", }, { Key: "hset-test-no-exist-1", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { // count is the number of field by hash key vals, err := db.HVals(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to HVals, err: %v", err) } t.Logf("key: %v, values: %v", testCase.Key, vals) } } ================================================ FILE: pkg/database/redis/redis_key_delete_test.go ================================================ /* *Copyright (c) 2023, kaydxh * *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 redis_test import ( "context" "flag" "fmt" "testing" ) var ( keyPrefix = flag.String("keyPrefix", "_JOB_SERVICE", "key prefix") deleteKeys = flag.Bool("deleteKeys", false, "delete keys") ) // GOOS=linux GOARCH=amd64 go test -c redis_key_delete_test.go redis_string_test.go //go test -v --count=1 --test.timeout=0 -test.run TestDeletePrefixKeys //go test -v --count=1 --test.timeout=0 -test.run TestDeletePrefixKeys -keyPrefix="test-" -deleteKeys=true func TestDeletePrefixKeys(t *testing.T) { db := GetDBOrDie() testCases := []struct { // KeyPrefix string // 是否有过期时间 ttl bool batch int64 // deleteKeys bool dump bool }{ { // KeyPrefix: "_JOB_SERVICE", ttl: false, batch: 500, // deleteKeys: false, dump: false, }, } ctx := context.Background() //ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) //defer cancel() var count int64 var deletedKeys []string for _, testCase := range testCases { t.Run(fmt.Sprintf("case-keyPrefix[%v]-deleteKeys[%v]", *keyPrefix, *deleteKeys), func(t *testing.T) { iter := db.Scan(ctx, 0, fmt.Sprintf("%s*", *keyPrefix), 0).Iterator() if err != nil { t.Fatalf("failed to scan key[%v], err: %v", *keyPrefix, err) } for iter.Next(ctx) { key := iter.Val() /* tp, err := db.Type(ctx, key).Result() if err != nil { t.Errorf("failed to type key[%v], err: %v", key, err) continue } switch tp { case redis_.TypeString: } */ /* value, err := db.Get(ctx, key).Result() if err != nil { t.Fatalf("failed to get key[%v], err: %v", key, err) } */ if testCase.dump { dumpVal, err := db.Dump(ctx, key).Result() if err != nil { t.Fatalf("failed to Dump, err: %v", err) } //t.Logf("key[%v], dumpValue[%v], value[%v]", key, dumpVal, value) t.Logf("key[%v], dumpValue[%v]", key, dumpVal) } //t.Logf("get key[%v] value[%v]", key, value) //todo delete if testCase.ttl { d, err := db.TTL(ctx, key).Result() if err != nil { t.Fatalf("failed to get key[%v], err: %v", key, err) } if d == -1 { // -1 means no TTL deletedKeys = append(deletedKeys, key) count++ } } else { count++ deletedKeys = append(deletedKeys, key) } if count%testCase.batch == 0 { if *deleteKeys { if err := db.Del(ctx, deletedKeys...).Err(); err != nil { t.Fatalf("failed to delete keys[%v], err: %v", key, err) } } deletedKeys = nil t.Logf("key number: %v ...", count) } } if err := iter.Err(); err != nil { t.Fatalf("failed to iter err: %v", err) } if len(deletedKeys) > 0 { if *deleteKeys { if err := db.Del(ctx, deletedKeys...).Err(); err != nil { t.Fatalf("failed to delete keys[%v], err: %v", deletedKeys, err) } } deletedKeys = nil t.Logf("key number: %v ...", count) } }) } t.Logf("all key number: %v", count) } ================================================ FILE: pkg/database/redis/redis_key_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis_test import ( "context" "testing" "time" ) //set key expired time s, if time > 0, time must > 1s func TestExpire(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Expiration time.Duration }{ { Key: "zset-test-1", Expiration: 30 * time.Millisecond, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { ok, err := db.Expire(ctx, testCase.Key, testCase.Expiration).Result() if err != nil { t.Fatalf("failed to Expire, err: %v", err) } t.Logf("set: %v, val: %v", testCase.Key, ok) } } //set key expired time with unix timestamp func TestExpireAt(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Tm time.Time }{ { Key: "zset-test-1", Tm: time.Now().Add(10 * time.Second), }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { ok, err := db.ExpireAt(ctx, testCase.Key, testCase.Tm).Result() if err != nil { t.Fatalf("failed to ExpireAt, err: %v", err) } if !ok { t.Fatalf("failed to ExpireAt") } t.Logf("set: %v, val: %v", testCase.Key, ok) } } //set key expired time, if time > 0, time must > 1ms func TestPExpire(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Expiration time.Duration }{ { Key: "zset-test-1", Expiration: 30 * time.Second, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { ok, err := db.PExpire(ctx, testCase.Key, testCase.Expiration).Result() if err != nil { t.Fatalf("failed to PExpire, err: %v", err) } t.Logf("set: %v, val: %v", testCase.Key, ok) } } //serialize key func TestDump(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "zset-test-1", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.Dump(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to Dump, err: %v", err) } t.Logf("set: %v, val: %v", testCase.Key, val) } } ================================================ FILE: pkg/database/redis/redis_list_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis_test import ( "context" "testing" "time" ) //push value to list key func TestRPush(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Value string }{ { Key: "list-test-1", Value: "value-list-test-1", }, { Key: "list-test-2", Value: "value-list-test-2", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.RPush(ctx, testCase.Key, testCase.Value).Result() if err != nil { t.Fatalf("failed to RPush, err: %v", err) } t.Logf("key: %v, val: %v", testCase.Key, val) } } //push value to list key which is existed func TestRPushX(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Value string }{ { Key: "list-test-3", Value: "value-list-test-1", }, { Key: "list-test-4", Value: "value-list-test-2", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.RPushX(ctx, testCase.Key, testCase.Value).Result() if err != nil { t.Fatalf("failed to RPushX, err: %v", err) } t.Logf("key: %v, val: %v", testCase.Key, val) } } //get length for list key func TestLLen(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "list-test-3", }, { Key: "list-test-4", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { length, err := db.LLen(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to LLen, err: %v", err) } t.Logf("list: %v, val: %v", testCase.Key, length) } } //push value to list key //Start: 0 the first element ,End //End: -1 the last element, -2, next to last element func TestLRange(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Start int64 End int64 }{ { Key: "list-test-1", Start: 0, End: -1, }, { Key: "list-test-2", Start: 0, End: -1, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { vals, err := db.LRange(ctx, testCase.Key, testCase.Start, testCase.End).Result() if err != nil { t.Fatalf("failed to LRange, err: %v", err) } t.Logf("list: %v, vals: %v", testCase.Key, vals) } } //can use negative indexes //-1 the last element, -2, next to last element func TestLIndex(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Index int64 }{ { Key: "list-test-1", Index: 0, }, { Key: "list-test-2", Index: -1, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.LIndex(ctx, testCase.Key, testCase.Index).Result() if err != nil { t.Fatalf("failed to LRange, err: %v", err) } t.Logf("list: %v, index: %v, val: %v", testCase.Key, testCase.Index, val) } } //insert value before the pivot func TestLInsertBefore(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Pivot string Value string }{ { Key: "list-test-1", Pivot: "value-list-test-1", Value: "value-list-test-2", }, { Key: "list-test-2", Pivot: "value-list-test-2", Value: "value-list-test-3", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.LInsertBefore(ctx, testCase.Key, testCase.Pivot, testCase.Value).Result() if err != nil { t.Fatalf("failed to LInsertBefore, err: %v", err) } t.Logf("list: %v, val: %v", testCase.Key, val) } } //insert value to list head func TestLPush(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Values []string }{ { Key: "list-test-1", Values: []string{"value-list-1-test-10", "value-list-1-test-20"}, }, { Key: "list-test-2", Values: []string{"value-list-2-test-10", "value-list-2-test-20"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.LPush(ctx, testCase.Key, testCase.Values).Result() if err != nil { t.Fatalf("failed to LInsertBefore, err: %v", err) } t.Logf("list: %v, val: %v", testCase.Key, val) } } //keep elements in range, the others will deleted func TestLTrim(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Start int64 End int64 }{ { Key: "list-test-1", Start: 1, End: 3, }, { Key: "list-test-2", Start: 0, End: -1, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.LTrim(ctx, testCase.Key, testCase.Start, testCase.End).Result() if err != nil { t.Fatalf("failed to LInsertBefore, err: %v", err) } t.Logf("list: %v, val: %v", testCase.Key, val) } } //delete element from list head, if the list is empty, will block times to find elements that can be ejected or wait timout func TestBLPop(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "list-test-1", }, { Key: "list-test-20", }, } timout := 5 * time.Second ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.BLPop(ctx, timout, testCase.Key).Result() if err != nil { t.Fatalf("failed to BLPop, err: %v", err) } t.Logf("list: %v, val: %v", testCase.Key, val) } } ================================================ FILE: pkg/database/redis/redis_options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis // A RedisOption sets options. type RedisOption interface { apply(*RedisClient) } // EmptyRedisUrlOption does not alter the Redisuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyRedisOption struct{} func (EmptyRedisOption) apply(*RedisClient) {} // RedisOptionFunc wraps a function that modifies Redis into an // implementation of the RedisOption interface. type RedisOptionFunc func(*RedisClient) func (f RedisOptionFunc) apply(do *RedisClient) { f(do) } // sample code for option, default for nothing to change func _RedisOptionWithDefault() RedisOption { return RedisOptionFunc(func(*RedisClient) { // nothing to change }) } func (o *RedisClient) ApplyOptions(options ...RedisOption) *RedisClient { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/database/redis/redis_set_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis_test import ( "context" "testing" "time" ) func TestSAdd(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Values []string }{ { Key: "set-test-1", Values: []string{ "values-set-test-1-1", "values-set-test-1-2", "values-set-test-1-3", "values-set-test-1-4", "values-set-test-1-5", }, }, { Key: "set-test-20", Values: []string{"values-set-test-1-1", "values-set-test-20-1", "values-set-test-20-2"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.SAdd(ctx, testCase.Key, testCase.Values).Result() if err != nil { t.Fatalf("failed to SAdd, err: %v", err) } t.Logf("set: %v, val: %v", testCase.Key, val) } } func TestSCard(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "set-test-1", }, { Key: "set-test-20", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { count, err := db.SCard(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to SCard, err: %v", err) } t.Logf("set: %v, member count: %v", testCase.Key, count) } } //diff val from multi sets // return the first set different elements from the other sets func TestSDiff(t *testing.T) { db := GetDBOrDie() testCases := []struct { Keys []string }{ { Keys: []string{"set-test-1", "set-test-20"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { vals, err := db.SDiff(ctx, testCase.Keys...).Result() if err != nil { t.Fatalf("failed to SDiff, err: %v", err) } t.Logf("sets: %v, diff values: %v", testCase.Keys, vals) } } func TestSDiffStore(t *testing.T) { db := GetDBOrDie() testCases := []struct { TargetSet string Keys []string }{ { TargetSet: "target-set", Keys: []string{"set-test-1", "set-test-20"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { //err: CROSSSLOT Keys in request don't hash to the same slot vals, err := db.SDiffStore(ctx, testCase.TargetSet, testCase.Keys...).Result() if err != nil { t.Fatalf("failed to SDiffStore, err: %v", err) } t.Logf("sets: %v, SDiffStore values: %v", testCase.Keys, vals) } } func TestSInter(t *testing.T) { db := GetDBOrDie() testCases := []struct { Keys []string }{ { Keys: []string{"set-test-1", "set-test-20"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { vals, err := db.SInter(ctx, testCase.Keys...).Result() if err != nil { t.Fatalf("failed to SDiffStore, err: %v", err) } t.Logf("sets: %v, SInter values: %v", testCase.Keys, vals) } } func TestSMembers(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "set-test-1", }, { Key: "set-test-20", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { vals, err := db.SMembers(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to SMembers, err: %v", err) } t.Logf("sets: %v, SMembers values: %v", testCase.Key, vals) } } func TestSInterStore(t *testing.T) { db := GetDBOrDie() testCases := []struct { TargetSet string Keys []string }{ { TargetSet: "target-inter-set", Keys: []string{"set-test-1", "set-test-20"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { //err: CROSSSLOT Keys in request don't hash to the same slot vals, err := db.SInterStore(ctx, testCase.TargetSet, testCase.Keys...).Result() if err != nil { t.Fatalf("failed to SInterStore, err: %v", err) } t.Logf("sets: %v, SInterStore values: %v", testCase.Keys, vals) } } //delete values from set func TestSRem(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Values []string }{ { Key: "set-test-1", Values: []string{"values-set-test-1-2"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { //err: CROSSSLOT Keys in request don't hash to the same slot vals, err := db.SRem(ctx, testCase.Key, testCase.Values).Result() if err != nil { t.Fatalf("failed to SRem, err: %v", err) } t.Logf("sets: %v, SRem values: %v", testCase.Key, vals) } } // check value is in set //need redis server version >= 6.2.0 func TestSMIsMember(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Values []string }{ { Key: "set-test-1", Values: []string{"values-set-test-1-2"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { //err: CROSSSLOT Keys in request don't hash to the same slot vals, err := db.SMIsMember(ctx, testCase.Key, testCase.Values).Result() if err != nil { t.Fatalf("failed to SMIsMember, err: %v", err) } t.Logf("sets: %v, SMIsMember values: %v", testCase.Key, vals) } } //random delete elemnt from set func TestSPop(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "set-test-1", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.SPop(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to SPop, err: %v", err) } t.Logf("sets: %v, SPop value: %v", testCase.Key, val) } } // random get value from set func TestSRandMember(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "set-test-1", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.SRandMember(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to SRandMember, err: %v", err) } t.Logf("sets: %v, SRandMember value: %v", testCase.Key, val) } } // random get value from set func TestSRandMemberN(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Count int64 }{ { Key: "set-test-1", Count: 2, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { vals, err := db.SRandMemberN(ctx, testCase.Key, testCase.Count).Result() if err != nil { t.Fatalf("failed to SRandMemberN, err: %v", err) } t.Logf("sets: %v, SRandMemberN values: %v", testCase.Key, vals) } } func TestSUnion(t *testing.T) { db := GetDBOrDie() testCases := []struct { Keys []string }{ { Keys: []string{"set-test-1", "set-test-20"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { //err: CROSSSLOT Keys in request don't hash to the same slot vals, err := db.SUnion(ctx, testCase.Keys...).Result() if err != nil { t.Fatalf("failed to SUnion, err: %v", err) } t.Logf("sets: %v, SUnion values: %v", testCase.Keys, vals) } } func TestSMove(t *testing.T) { db := GetDBOrDie() testCases := []struct { Source string Destination string Value string }{ { Source: "set-test-1", Destination: "set-test-20", Value: "values-set-test-1-5", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { //err: CROSSSLOT Keys in request don't hash to the same slot ok, err := db.SMove(ctx, testCase.Source, testCase.Destination, testCase.Value).Result() if err != nil { t.Fatalf("failed to SUnion, err: %v", err) } t.Logf("move sets: %v to %v, SUnion values: %v", testCase.Source, testCase.Destination, ok) } } func TestSUnionStore(t *testing.T) { db := GetDBOrDie() testCases := []struct { TargetSet string Keys []string }{ { TargetSet: "target-set", Keys: []string{"set-test-1", "set-test-20"}, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { //err: CROSSSLOT Keys in request don't hash to the same slot val, err := db.SUnionStore(ctx, testCase.TargetSet, testCase.Keys...).Result() if err != nil { t.Fatalf("failed to SUnionStore, err: %v", err) } t.Logf("sets: %v, SUnionStore values: %v", testCase.Keys, val) } } func TestSScan(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Cursor uint64 Match string Count int64 }{ { Key: "set-test-1", Cursor: 0, Match: "*set*", Count: 2, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { //err: CROSSSLOT Keys in request don't hash to the same slot keys, cursor, err := db.SScan(ctx, testCase.Key, testCase.Cursor, testCase.Match, testCase.Count).Result() if err != nil { t.Fatalf("failed to SScan, err: %v", err) } t.Logf("sets: %v,SScan keys: %v, cursor: %v", testCase.Key, keys, cursor) } } ================================================ FILE: pkg/database/redis/redis_string_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis_test import ( "sync" "testing" "time" "context" "github.com/go-redis/redis/v8" redis_ "github.com/kaydxh/golang/pkg/database/redis" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/stretchr/testify/assert" ) func TestGetDataBase(t *testing.T) { testCases := []struct { TestName string Addresses []string DB int UserName string Password string }{ { TestName: "test1", Addresses: []string{"9.135.232.102:6380"}, DB: 0, UserName: "root", Password: "HXufW*3569FShs", }, } for _, testCase := range testCases { t.Run(testCase.TestName, func(t *testing.T) { db := redis_.NewRedisClient(redis_.DBConfig{ Addresses: testCase.Addresses, UserName: testCase.UserName, Password: testCase.Password, DB: testCase.DB, }) redisDB, err := db.GetRedis(context.Background()) if err != nil { t.Fatalf("failed to get redis database: %v, got : %s", testCase.Addresses, err) } assert.NotNil(t, redisDB) }) } } var ( once sync.Once db *redis.Client err error ) func GetDBOrDie() *redis.Client { once.Do(func() { cfgFile := "./redis.yaml" config := redis_.NewConfig(redis_.WithViper(viper_.GetViper(cfgFile, "database.redis"))) db, err = config.Complete().New(context.Background()) if err != nil { panic(err) } if db == nil { panic("db is not enable") } }) return db } func TestNew(t *testing.T) { db := GetDBOrDie() //defer db.Close() t.Logf("db: %#v", db) } // set string // Redis `SET key value [expiration]` command. // // Use expiration for `SETEX`-like behavior. // Zero expiration means the key has no expiration time. func TestSet(t *testing.T) { db := GetDBOrDie() //defer db.Close() testCases := []struct { key string value string expire time.Duration expected string }{ { key: "test1", value: "test1-1, test1-2", expected: "test1", }, { key: "test2", value: "test2-1, test2-2", expected: "test2", }, { key: "test3-tmp", value: "test3-1, test3-2", expire: time.Minute, expected: "test3", }, } ctx := context.Background() for _, testCase := range testCases { result, err := db.Set(ctx, testCase.key, testCase.value, testCase.expire).Result() if err != nil { t.Fatalf("failed to set string, err: %v", err) } t.Logf("result of %v: %v", testCase.key, result) } } //get values with keys func TestGetValues(t *testing.T) { db := GetDBOrDie() // defer db.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() keys, err := db.Keys(ctx, "*").Result() if err != nil { t.Fatalf("failed to get all keys , err: %v", err) } values, err := redis_.GetValues(ctx, db, keys...) if err != nil { t.Fatalf("failed to get values, err: %v", err) } t.Logf("keys: %v, values: %v", keys, values) } //get range of value with key func TestGetRange(t *testing.T) { db := GetDBOrDie() // defer db.Close() testCases := []struct { key string start int64 end int64 expected string }{ { key: "test1", start: 0, end: -1, // get all range expected: "test1-1", }, { key: "test2", start: 0, end: int64(len("test1-1")) - 1, //include end expected: "test2-1", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { value, err := db.GetRange(ctx, testCase.key, testCase.start, testCase.end).Result() if err != nil { t.Fatalf("failed to get range, err: %v", err) } t.Logf("key: %v, range [%d:%d] value: %v", testCase.key, testCase.start, testCase.end, value) } } ================================================ FILE: pkg/database/redis/redis_transaction_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis_test import ( "context" "testing" "time" "github.com/go-redis/redis/v8" ) // transaction, but not support rollback, ensure only the client command execed func TestTxPipelined(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Field string Incr int64 }{ { Key: "hset-test-1", Field: "redis_id", Incr: 1, }, { Key: "hset-test-2", Field: "redis_id", Incr: 2, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _, err := db.TxPipelined(ctx, func(redis.Pipeliner) error { for _, testCase := range testCases { val, err := db.HIncrBy(ctx, testCase.Key, testCase.Field, testCase.Incr).Result() if err != nil { return err } t.Logf("set: %v, val: %v", testCase.Key, val) } return nil }) if err != nil { t.Fatalf("failed to TxPipelined, err: %v", err) } } ================================================ FILE: pkg/database/redis/redis_type.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis import ( "sync/atomic" "github.com/go-redis/redis/v8" ) const ( TypeString = "string" TypeHash = "hash" TypeList = "list" TypeSet = "set" TypeZSet = "zset" TypeOther = "other" ) type RedisDB atomic.Value //check type RedisDB* whether to implement interface of atomic.Value //var _ atomic.Value = (*RedisDB)(nil) //check type RedisDB whether to implement interface of atomic.Value //var _ atomic.Value = RedisDB{} func (m *RedisDB) Store(value *redis.Client) { (*atomic.Value)(m).Store(value) } func (m *RedisDB) Load() *redis.Client { value := (*atomic.Value)(m).Load() if value == nil { return nil } return value.(*redis.Client) } ================================================ FILE: pkg/database/redis/redis_zset_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 redis_test import ( "context" "testing" "time" "github.com/go-redis/redis/v8" ) func TestZAdd(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Value string Score float64 }{ { Key: "zset-test-1", Value: "values-zset-test-1-1", Score: 0.5, }, { Key: "zset-test-1", Value: "values-zset-test-1-2", Score: 50, }, { Key: "zset-test-1", Value: "values-zset-test-1-3", Score: 500, }, { Key: "zset-test-1", Value: "values-zset-test-1-4", Score: 100, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { val, err := db.ZAdd(ctx, testCase.Key, &redis.Z{ Score: testCase.Score, Member: testCase.Value, }).Result() if err != nil { t.Fatalf("failed to ZAdd, err: %v", err) } t.Logf("set: %v, val: %v", testCase.Key, val) } } func TestZCard(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string }{ { Key: "zset-test-1", }, { Key: "zset-test-20", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { count, err := db.ZCard(ctx, testCase.Key).Result() if err != nil { t.Fatalf("failed to ZCard, err: %v", err) } t.Logf("set: %v, member count: %v", testCase.Key, count) } } // return values sorted by score func TestZRange(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Start int64 Stop int64 }{ { Key: "zset-test-1", Start: 0, Stop: -1, }, { Key: "zset-test-20", Start: 0, Stop: -1, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { vals, err := db.ZRange(ctx, testCase.Key, testCase.Start, testCase.Stop).Result() if err != nil { t.Fatalf("failed to ZRange, err: %v", err) } t.Logf("set: %v, members: %v", testCase.Key, vals) } } func TestZRangeByScore(t *testing.T) { db := GetDBOrDie() testCases := []struct { Key string Min string Max string }{ { Key: "zset-test-1", Min: "50", Max: "100", }, { Key: "zset-test-1", Min: "-inf", Max: "+inf", }, { Key: "zset-test-1", Min: "-1", Max: "100", }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for _, testCase := range testCases { vals, err := db.ZRangeByScore(ctx, testCase.Key, &redis.ZRangeBy{ Min: testCase.Min, Max: testCase.Max, }).Result() if err != nil { t.Fatalf("failed to ZRangeByScore, err: %v", err) } t.Logf("set: %v, ZRangeByScore: %v", testCase.Key, vals) } } ================================================ FILE: pkg/discovery/consul/discovery.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 consul import ( "context" "fmt" "net" "strconv" "sync" "time" "github.com/hashicorp/consul/api" "github.com/kaydxh/golang/go/errors" "github.com/sirupsen/logrus" "go.uber.org/atomic" ) type ServiceRegistryServer struct { ConsulAddress string ServiceId string ServiceName string Tag []string Ip string Port int TTL time.Duration CheckInterval time.Duration inShutdown atomic.Bool // true when when server is in shutdown mu sync.Mutex cancel func() } func NewServiceRegistry( consulAddr string, serviceName string, serviceAddress string, ) (*ServiceRegistryServer, error) { logger := logrus.WithField("module", "service_registry"). WithField("service_name", serviceName). WithField("addr", serviceAddress) host, port, err := net.SplitHostPort(serviceAddress) if err != nil { logger.WithError(err).Errorln("malformed service serviceAddress") return nil, fmt.Errorf("malformed service serviceAddress: %w", err) } nport, err := strconv.Atoi(port) if err != nil { logger.WithField("port", port). WithError(err). Errorln("malformed service port, must be a number") return nil, fmt.Errorf("malformed service port: %w", err) } serviceId := fmt.Sprintf("%v-%v-%v", serviceName, host, port) s := &ServiceRegistryServer{ ConsulAddress: consulAddr, ServiceId: serviceId, ServiceName: serviceName, Tag: []string{}, Port: nport, Ip: host, TTL: 300 * time.Second, CheckInterval: 10 * time.Second, } return s, nil } // Run will initialize the backend. It must not block, but may run go routines in the background. func (srv *ServiceRegistryServer) Run(ctx context.Context) error { logger := srv.logger(). WithField("service_name", srv.ServiceName). WithField("service_id", srv.ServiceId) logger.Infoln("ConsulRegistry Run") if srv.inShutdown.Load() { logger.Infoln("ConsulRegistry Shutdown") return fmt.Errorf("server closed") } go func() { errors.HandleError(srv.Serve(ctx)) }() return nil } func (srv *ServiceRegistryServer) Serve(ctx context.Context) error { logger := srv.logger(). WithField("service_name", srv.ServiceName). WithField("service_id", srv.ServiceId) logger.Infoln("ConsulRegistry Serve") if srv.inShutdown.Load() { logger.Infoln("ConsulRegistry Shutdown") return fmt.Errorf("server closed") } defer srv.inShutdown.Store(true) ctx, cancel := context.WithCancel(ctx) srv.mu.Lock() srv.cancel = cancel srv.mu.Unlock() t := time.NewTicker(time.Second * 30) defer t.Stop() for { select { case <-t.C: logger.Infoln("registering service to consul") err := srv.Register() if err != nil { logger.WithError(err).Errorln("register service failed") continue } srv.logger().Info("register service by consul") case <-ctx.Done(): logger.Infoln("unregistering service to consul") err := srv.UnRegister() if err != nil { logger.WithError(err).Errorln("unregister service failed") return err } srv.logger().Info("unregister service by consul") return nil } } } func (srv *ServiceRegistryServer) Shutdown() { srv.inShutdown.Store(true) srv.mu.Lock() defer srv.mu.Unlock() if srv.cancel != nil { srv.cancel() } } func (srv *ServiceRegistryServer) Register() error { config := api.DefaultConfig() config.Address = srv.ConsulAddress client, err := api.NewClient(config) if err != nil { return err } agent := client.Agent() checkUrl := fmt.Sprintf("http://%v:%v/api/%v/v1/health", srv.Ip, srv.Port, srv.ServiceName) reg := &api.AgentServiceRegistration{ ID: srv.ServiceId, Name: srv.ServiceName, Tags: srv.Tag, Port: srv.Port, Address: srv.Ip, Check: &api.AgentServiceCheck{ Interval: srv.CheckInterval.String(), HTTP: checkUrl, DeregisterCriticalServiceAfter: srv.TTL.String(), }, } return agent.ServiceRegister(reg) } func (srv *ServiceRegistryServer) UnRegister() error { config := api.DefaultConfig() config.Address = srv.ConsulAddress client, err := api.NewClient(config) if err != nil { return err } return client.Agent().ServiceDeregister(srv.ServiceId) } func (srv *ServiceRegistryServer) logger() logrus.FieldLogger { return logrus. WithField("module", "service_registry"). WithField("consul", srv.ConsulAddress). WithField("service_name", srv.ServiceName). WithField("service_id", srv.ServiceId). WithField("ip", srv.Ip).WithField("port", srv.Port) } ================================================ FILE: pkg/discovery/etcd/config.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 etcd import ( "context" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) type Config struct { Proto Etcd opts struct { // If set, overrides params below viper *viper.Viper } } type completedConfig struct { *Config completeError error } type CompletedConfig struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig } func (c *completedConfig) New(ctx context.Context, createCallbackFunc, deleteCallbackFunc EventCallbackFunc) (*EtcdKV, error) { logrus.Infof("Installing Etcd") if c.completeError != nil { return nil, c.completeError } if !c.Proto.GetEnabled() { logrus.Warnf("Etcd disenabled") return nil, nil } etcdKV, err := c.install(ctx, createCallbackFunc, deleteCallbackFunc) if err != nil { return nil, err } logrus.Infof("Installed Etcd") return etcdKV, nil } func (c *completedConfig) install(ctx context.Context, createCallbackFunc, deleteCallbackFunc EventCallbackFunc) (*EtcdKV, error) { etcdKV := NewEtcdKV( EtcdConfig{ Addresses: c.Proto.GetAddresses(), UserName: c.Proto.GetUsername(), Password: c.Proto.GetPassword(), }, WithDialTimeout(c.Proto.GetDialTimeout().AsDuration()), WithMaxCallRecvMsgSize(int(c.Proto.MaxCallRecvMsgSize)), WithMaxCallSendMsgSize(int(c.Proto.MaxCallSendMsgSize)), WithAutoSyncInterval(c.Proto.GetAutoSyncInterval().AsDuration()), WithWatchPaths(c.Proto.WatchPaths), WithWatchCreateCallbackFunc(createCallbackFunc), WithWatchDeleteCallbackFunc(deleteCallbackFunc), ) _, err := etcdKV.GetKVUntil( ctx, c.Proto.GetMaxWaitDuration().AsDuration(), c.Proto.GetFailAfterDuration().AsDuration(), ) if err != nil { return nil, err } etcdKV.Watch(ctx) return etcdKV, nil } // Complete set default ServerRunOptions. func (c *Config) Complete() CompletedConfig { err := c.loadViper() if err != nil { return CompletedConfig{&completedConfig{ Config: c, completeError: err, }} } return CompletedConfig{&completedConfig{Config: c}} } func (c *Config) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, &c.Proto) } return nil } func NewConfig(options ...ConfigOption) *Config { c := &Config{} c.ApplyOptions(options...) return c } ================================================ FILE: pkg/discovery/etcd/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 etcd import ( "github.com/spf13/viper" ) func WithViper(v *viper.Viper) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.viper = v }) } ================================================ FILE: pkg/discovery/etcd/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 etcd // A ConfigOption sets options. type ConfigOption interface { apply(*Config) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption struct{} func (EmptyConfigOption) apply(*Config) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc func(*Config) func (f ConfigOptionFunc) apply(do *Config) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault() ConfigOption { return ConfigOptionFunc(func(*Config) { // nothing to change }) } func (o *Config) ApplyOptions(options ...ConfigOption) *Config { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/discovery/etcd/etcd.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 etcd import ( "context" "fmt" "path/filepath" "sync" "time" clientv3 "go.etcd.io/etcd/client/v3" "go.etcd.io/etcd/client/v3/concurrency" time_ "github.com/kaydxh/golang/go/time" "github.com/sirupsen/logrus" ) type EventCallbackFunc func(ctx context.Context, key, value string) var ( etcdKV ETCDKV mu sync.Mutex ) // Default values for Etcd. const ( DefaultDialTimeout = 5 * time.Second DefaultLockTTL = 15 * time.Second ) type EtcdConfig struct { Addresses []string UserName string Password string } type EtcdKVOptions struct { DialTimeout time.Duration MaxCallSendMsgSize int MaxCallRecvMsgSize int AutoSyncInterval time.Duration LockPrefixPath string LockKey string LockTTL time.Duration WatchPaths []string CreateCallbackFunc EventCallbackFunc DeleteCallbackFunc EventCallbackFunc } type EtcdKV struct { Conf EtcdConfig *clientv3.Client session *concurrency.Session mutex *concurrency.Mutex opts EtcdKVOptions } func NewEtcdKV(conf EtcdConfig, opts ...EtcdKVOption) *EtcdKV { kv := &EtcdKV{ Conf: conf, } kv.ApplyOptions(opts...) if kv.opts.DialTimeout == 0 { kv.opts.DialTimeout = DefaultDialTimeout } if kv.opts.LockTTL == 0 { kv.opts.LockTTL = DefaultLockTTL } return kv } func GetKV() *clientv3.Client { return etcdKV.Load() } func CloseKV() error { if etcdKV.Load() == nil { return nil } return etcdKV.Load().Close() } func (d *EtcdKV) GetKV(ctx context.Context) (*clientv3.Client, error) { if d.Client != nil { return d.Client, nil } if len(d.Conf.Addresses) == 0 { return nil, fmt.Errorf("invalid etcd address") } logrus.Infof("dialTimeout: %v", d.opts.DialTimeout) kv, err := clientv3.New(clientv3.Config{ Endpoints: d.Conf.Addresses, Context: ctx, Username: d.Conf.UserName, Password: d.Conf.Password, MaxCallRecvMsgSize: d.opts.MaxCallRecvMsgSize, MaxCallSendMsgSize: d.opts.MaxCallSendMsgSize, AutoSyncInterval: d.opts.AutoSyncInterval, DialTimeout: d.opts.DialTimeout, }) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(ctx, d.opts.DialTimeout) defer cancel() status, err := kv.Status(ctx, d.Conf.Addresses[0]) if err != nil { return nil, err } logrus.Infof("kv status: %v", status) d.Client = kv etcdKV.Store(kv) return kv, nil } func (d *EtcdKV) GetKVUntil( ctx context.Context, maxWaitInterval time.Duration, failAfter time.Duration, ) (*clientv3.Client, error) { var kv *clientv3.Client exp := time_.NewExponentialBackOff( time_.WithExponentialBackOffOptionMaxInterval(maxWaitInterval), time_.WithExponentialBackOffOptionMaxElapsedTime(failAfter), ) err := time_.BackOffUntilWithContext(ctx, func(ctx context.Context) (err_ error) { kv, err_ = d.GetKV(ctx) if err_ != nil { return err_ } return nil }, exp, true, false) if err != nil { return nil, fmt.Errorf("get etcd fail after: %v", failAfter) } return kv, nil } func (d *EtcdKV) Watch(ctx context.Context) { for _, path := range d.opts.WatchPaths { fmt.Printf("watch path: %v\n", path) Watch(ctx, d.Client, path, d.opts.CreateCallbackFunc, d.opts.DeleteCallbackFunc) } } func (d *EtcdKV) Close() error { if d.Client == nil { return fmt.Errorf("no etcd pool") } return d.Client.Close() } func (d *EtcdKV) Lock(ctx context.Context, opts ...EtcdKVOption) error { d.ApplyOptions(opts...) lockTTL := d.opts.LockTTL session, err := concurrency.NewSession(d.Client, concurrency.WithContext(ctx), concurrency.WithTTL(int(lockTTL.Seconds()))) if err != nil { return err } keyPath := filepath.Join(d.opts.LockPrefixPath, d.opts.LockKey) mutex := concurrency.NewMutex(session, keyPath) if err := mutex.Lock(ctx); err != nil { return err } go func() { select { case <-ctx.Done(): logrus.Infof("lock[%v]'s context is done, err: %v", keyPath, ctx.Err()) case <-session.Done(): logrus.Infof("lock[%v]'s session is done", keyPath) } }() d.session = session d.mutex = mutex return nil } func (d *EtcdKV) Unlock(ctx context.Context) error { if d.mutex == nil { return fmt.Errorf("lock mutx is nil") } err := d.mutex.Unlock(ctx) if err != nil { return err } return d.session.Close() } func (d *EtcdKV) TxPipelined(ctx context.Context, cmps []clientv3.Cmp, doOps, elOps []clientv3.Op) error { txn := d.Client.Txn(ctx) resp, err := txn.If(cmps...).Then(doOps...).Else(elOps...).Commit() if err != nil { return err } if resp.Succeeded { return nil } return fmt.Errorf("condition not meet, run else ops in transaction") } ================================================ FILE: pkg/discovery/etcd/etcd.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 etcd import ( "time" ) func WithDialTimeout(dialTimeout time.Duration) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.DialTimeout = dialTimeout }) } func WithMaxCallRecvMsgSize(msgSize int) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.MaxCallRecvMsgSize = msgSize }) } func WithMaxCallSendMsgSize(msgSize int) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.MaxCallSendMsgSize = msgSize }) } func WithAutoSyncInterval(autoSyncInterval time.Duration) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.AutoSyncInterval = autoSyncInterval }) } func WithWatchPaths(paths []string) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.WatchPaths = paths }) } func WithWatchCreateCallbackFunc(f EventCallbackFunc) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.CreateCallbackFunc = f }) } func WithWatchDeleteCallbackFunc(f EventCallbackFunc) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.DeleteCallbackFunc = f }) } func WithLockTTL(ttl time.Duration) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.LockTTL = ttl }) } func WithLockPrefixPath(prefix string) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.LockPrefixPath = prefix }) } func WithLockKey(key string) EtcdKVOption { return EtcdKVOptionFunc(func(c *EtcdKV) { c.opts.LockKey = key }) } ================================================ FILE: pkg/discovery/etcd/etcd.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v4.24.2 // source: pkg/discovery/etcd/etcd.proto package etcd import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" durationpb "google.golang.org/protobuf/types/known/durationpb" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Etcd struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` Addresses []string `protobuf:"bytes,2,rep,name=addresses,proto3" json:"addresses,omitempty"` Username string `protobuf:"bytes,3,opt,name=username,proto3" json:"username,omitempty"` Password string `protobuf:"bytes,4,opt,name=password,proto3" json:"password,omitempty"` MaxCallSendMsgSize int32 `protobuf:"varint,5,opt,name=max_call_send_msg_size,json=maxCallSendMsgSize,proto3" json:"max_call_send_msg_size,omitempty"` //If 0, it defaults to 2.0 MiB (2 * 1024 * 1024) // MaxCallRecvMsgSize is the client-side response receive limit. // If 0, it defaults to "math.MaxInt32", because range response can // easily exceed request send limits. // Make sure that "MaxCallRecvMsgSize" >= server-side default // send/recv limit. // ("--max-request-bytes" flag to etcd or // "embed.Config.MaxRequestBytes"). MaxCallRecvMsgSize int32 `protobuf:"varint,6,opt,name=max_call_recv_msg_size,json=maxCallRecvMsgSize,proto3" json:"max_call_recv_msg_size,omitempty"` // AutoSyncInterval is the interval to update endpoints with its latest members. // 0 disables auto-sync. By default auto-sync is disabled. AutoSyncInterval *durationpb.Duration `protobuf:"bytes,7,opt,name=auto_sync_interval,json=autoSyncInterval,proto3" json:"auto_sync_interval,omitempty"` DialTimeout *durationpb.Duration `protobuf:"bytes,8,opt,name=dial_timeout,json=dialTimeout,proto3" json:"dial_timeout,omitempty"` MaxWaitDuration *durationpb.Duration `protobuf:"bytes,12,opt,name=max_wait_duration,json=maxWaitDuration,proto3" json:"max_wait_duration,omitempty"` FailAfterDuration *durationpb.Duration `protobuf:"bytes,13,opt,name=fail_after_duration,json=failAfterDuration,proto3" json:"fail_after_duration,omitempty"` WatchPaths []string `protobuf:"bytes,14,rep,name=watch_paths,json=watchPaths,proto3" json:"watch_paths,omitempty"` } func (x *Etcd) Reset() { *x = Etcd{} if protoimpl.UnsafeEnabled { mi := &file_pkg_discovery_etcd_etcd_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Etcd) String() string { return protoimpl.X.MessageStringOf(x) } func (*Etcd) ProtoMessage() {} func (x *Etcd) ProtoReflect() protoreflect.Message { mi := &file_pkg_discovery_etcd_etcd_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Etcd.ProtoReflect.Descriptor instead. func (*Etcd) Descriptor() ([]byte, []int) { return file_pkg_discovery_etcd_etcd_proto_rawDescGZIP(), []int{0} } func (x *Etcd) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *Etcd) GetAddresses() []string { if x != nil { return x.Addresses } return nil } func (x *Etcd) GetUsername() string { if x != nil { return x.Username } return "" } func (x *Etcd) GetPassword() string { if x != nil { return x.Password } return "" } func (x *Etcd) GetMaxCallSendMsgSize() int32 { if x != nil { return x.MaxCallSendMsgSize } return 0 } func (x *Etcd) GetMaxCallRecvMsgSize() int32 { if x != nil { return x.MaxCallRecvMsgSize } return 0 } func (x *Etcd) GetAutoSyncInterval() *durationpb.Duration { if x != nil { return x.AutoSyncInterval } return nil } func (x *Etcd) GetDialTimeout() *durationpb.Duration { if x != nil { return x.DialTimeout } return nil } func (x *Etcd) GetMaxWaitDuration() *durationpb.Duration { if x != nil { return x.MaxWaitDuration } return nil } func (x *Etcd) GetFailAfterDuration() *durationpb.Duration { if x != nil { return x.FailAfterDuration } return nil } func (x *Etcd) GetWatchPaths() []string { if x != nil { return x.WatchPaths } return nil } var File_pkg_discovery_etcd_etcd_proto protoreflect.FileDescriptor var file_pkg_discovery_etcd_etcd_proto_rawDesc = []byte{ 0x0a, 0x1d, 0x70, 0x6b, 0x67, 0x2f, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2f, 0x65, 0x74, 0x63, 0x64, 0x2f, 0x65, 0x74, 0x63, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2e, 0x65, 0x74, 0x63, 0x64, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x98, 0x04, 0x0a, 0x04, 0x45, 0x74, 0x63, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x32, 0x0a, 0x16, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x61, 0x6c, 0x6c, 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x6d, 0x73, 0x67, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x12, 0x6d, 0x61, 0x78, 0x43, 0x61, 0x6c, 0x6c, 0x53, 0x65, 0x6e, 0x64, 0x4d, 0x73, 0x67, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x32, 0x0a, 0x16, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x61, 0x6c, 0x6c, 0x5f, 0x72, 0x65, 0x63, 0x76, 0x5f, 0x6d, 0x73, 0x67, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x52, 0x12, 0x6d, 0x61, 0x78, 0x43, 0x61, 0x6c, 0x6c, 0x52, 0x65, 0x63, 0x76, 0x4d, 0x73, 0x67, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x47, 0x0a, 0x12, 0x61, 0x75, 0x74, 0x6f, 0x5f, 0x73, 0x79, 0x6e, 0x63, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x10, 0x61, 0x75, 0x74, 0x6f, 0x53, 0x79, 0x6e, 0x63, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x3c, 0x0a, 0x0c, 0x64, 0x69, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x45, 0x0a, 0x11, 0x6d, 0x61, 0x78, 0x5f, 0x77, 0x61, 0x69, 0x74, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x6d, 0x61, 0x78, 0x57, 0x61, 0x69, 0x74, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x49, 0x0a, 0x13, 0x66, 0x61, 0x69, 0x6c, 0x5f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x11, 0x66, 0x61, 0x69, 0x6c, 0x41, 0x66, 0x74, 0x65, 0x72, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1f, 0x0a, 0x0b, 0x77, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x73, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0a, 0x77, 0x61, 0x74, 0x63, 0x68, 0x50, 0x61, 0x74, 0x68, 0x73, 0x42, 0x2e, 0x5a, 0x2c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2e, 0x65, 0x74, 0x63, 0x64, 0x3b, 0x65, 0x74, 0x63, 0x64, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_pkg_discovery_etcd_etcd_proto_rawDescOnce sync.Once file_pkg_discovery_etcd_etcd_proto_rawDescData = file_pkg_discovery_etcd_etcd_proto_rawDesc ) func file_pkg_discovery_etcd_etcd_proto_rawDescGZIP() []byte { file_pkg_discovery_etcd_etcd_proto_rawDescOnce.Do(func() { file_pkg_discovery_etcd_etcd_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_discovery_etcd_etcd_proto_rawDescData) }) return file_pkg_discovery_etcd_etcd_proto_rawDescData } var file_pkg_discovery_etcd_etcd_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_pkg_discovery_etcd_etcd_proto_goTypes = []interface{}{ (*Etcd)(nil), // 0: go.pkg.discovery.etcd.Etcd (*durationpb.Duration)(nil), // 1: google.protobuf.Duration } var file_pkg_discovery_etcd_etcd_proto_depIdxs = []int32{ 1, // 0: go.pkg.discovery.etcd.Etcd.auto_sync_interval:type_name -> google.protobuf.Duration 1, // 1: go.pkg.discovery.etcd.Etcd.dial_timeout:type_name -> google.protobuf.Duration 1, // 2: go.pkg.discovery.etcd.Etcd.max_wait_duration:type_name -> google.protobuf.Duration 1, // 3: go.pkg.discovery.etcd.Etcd.fail_after_duration:type_name -> google.protobuf.Duration 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_pkg_discovery_etcd_etcd_proto_init() } func file_pkg_discovery_etcd_etcd_proto_init() { if File_pkg_discovery_etcd_etcd_proto != nil { return } if !protoimpl.UnsafeEnabled { file_pkg_discovery_etcd_etcd_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Etcd); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_pkg_discovery_etcd_etcd_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_pkg_discovery_etcd_etcd_proto_goTypes, DependencyIndexes: file_pkg_discovery_etcd_etcd_proto_depIdxs, MessageInfos: file_pkg_discovery_etcd_etcd_proto_msgTypes, }.Build() File_pkg_discovery_etcd_etcd_proto = out.File file_pkg_discovery_etcd_etcd_proto_rawDesc = nil file_pkg_discovery_etcd_etcd_proto_goTypes = nil file_pkg_discovery_etcd_etcd_proto_depIdxs = nil } ================================================ FILE: pkg/discovery/etcd/etcd.proto ================================================ syntax = "proto3"; package go.pkg.discovery.etcd; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/go.pkg.discovery.etcd;etcd"; message Etcd { bool enabled = 1; repeated string addresses = 2; string username = 3; string password = 4; int32 max_call_send_msg_size = 5; //If 0, it defaults to 2.0 MiB (2 * 1024 * 1024) // MaxCallRecvMsgSize is the client-side response receive limit. // If 0, it defaults to "math.MaxInt32", because range response can // easily exceed request send limits. // Make sure that "MaxCallRecvMsgSize" >= server-side default // send/recv limit. // ("--max-request-bytes" flag to etcd or // "embed.Config.MaxRequestBytes"). int32 max_call_recv_msg_size = 6; // AutoSyncInterval is the interval to update endpoints with its latest members. // 0 disables auto-sync. By default auto-sync is disabled. google.protobuf.Duration auto_sync_interval = 7; google.protobuf.Duration dial_timeout = 8; google.protobuf.Duration max_wait_duration = 12; google.protobuf.Duration fail_after_duration = 13; repeated string watch_paths = 14; } ================================================ FILE: pkg/discovery/etcd/etcd.watch.go ================================================ package etcd import ( "context" "go.etcd.io/etcd/api/v3/mvccpb" clientv3 "go.etcd.io/etcd/client/v3" ) func Watch(ctx context.Context, kv *clientv3.Client, key string, createCallbackFunc, deleteCallbackFunc EventCallbackFunc) { ch := kv.Watch(ctx, key, clientv3.WithPrefix(), clientv3.WithCreatedNotify()) go func() error { for resp := range ch { for _, event := range resp.Events { switch event.Type { case mvccpb.PUT: if createCallbackFunc != nil { createCallbackFunc(ctx, string(event.Kv.Key), string(event.Kv.Value)) } case mvccpb.DELETE: if deleteCallbackFunc != nil { deleteCallbackFunc(ctx, string(event.Kv.Key), string(event.Kv.Value)) } } } } return nil }() return } ================================================ FILE: pkg/discovery/etcd/etcd.yaml ================================================ discovery: etcd: enabled: true addresses: - "9.135.121.151:2379" username: "" password: "" max_call_send_msg_size: 0 max_call_recv_msg_size: 0 auto_sync_interval: 0s dial_timeout: 5s max_wait_duration: 20s fail_after_duration: 60s watch_paths: - "foo" ================================================ FILE: pkg/discovery/etcd/etcd_options.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 etcd // A EtcdKVOption sets options. type EtcdKVOption interface { apply(*EtcdKV) } // EmptyEtcdKVUrlOption does not alter the EtcdKVuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyEtcdKVOption struct{} func (EmptyEtcdKVOption) apply(*EtcdKV) {} // EtcdKVOptionFunc wraps a function that modifies EtcdKV into an // implementation of the EtcdKVOption interface. type EtcdKVOptionFunc func(*EtcdKV) func (f EtcdKVOptionFunc) apply(do *EtcdKV) { f(do) } // sample code for option, default for nothing to change func _EtcdKVOptionWithDefault() EtcdKVOption { return EtcdKVOptionFunc(func(*EtcdKV) { // nothing to change }) } func (o *EtcdKV) ApplyOptions(options ...EtcdKVOption) *EtcdKV { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/discovery/etcd/etcd_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 etcd_test import ( "context" "fmt" "testing" "time" etcd_ "github.com/kaydxh/golang/pkg/discovery/etcd" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" clientv3 "go.etcd.io/etcd/client/v3" ) func TestGetKV(t *testing.T) { testCases := []struct { Addresses []string }{ { Addresses: []string{"9.135.121.151:2379"}, }, } ctx := context.Background() for i, testCase := range testCases { t.Run(fmt.Sprintf("name-%d", i), func(t *testing.T) { kv := etcd_.NewEtcdKV(etcd_.EtcdConfig{ Addresses: testCase.Addresses, }) etcdKV, err := kv.GetKV(ctx) if err != nil { t.Fatalf("failed to get kv: %v, got : %s", testCase.Addresses, err) } assert.NotNil(t, etcdKV) }) } } func TestGetKVUntil(t *testing.T) { testCases := []struct { Addresses []string DailTimeout time.Duration }{ { Addresses: []string{"9.135.121.151:2379"}, DailTimeout: 3 * time.Second, }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("name-%d", i), func(t *testing.T) { db := etcd_.NewEtcdKV(etcd_.EtcdConfig{ Addresses: testCase.Addresses, }, etcd_.WithDialTimeout(testCase.DailTimeout)) sqlDB, err := db.GetKVUntil(context.Background(), 5*time.Second, 20*time.Second) if err != nil { t.Fatalf("failed to get kv: %v, got : %s", testCase.Addresses, err) } assert.NotNil(t, sqlDB) }) } } func CreateCallback(ctx context.Context, key, value string) { logrus.Infof("create key: %v, value: %v", key, value) } func DeleteCallback(ctx context.Context, key, value string) { logrus.Infof("delete key: %v, value: %v", key, value) } func InstallEtcd(ctx context.Context) (*etcd_.EtcdKV, error) { cfgFile := "./etcd.yaml" config := etcd_.NewConfig(etcd_.WithViper(viper_.GetViper(cfgFile, "discovery.etcd"))) kv, err := config.Complete().New(ctx, CreateCallback, DeleteCallback) if err != nil { logrus.Errorf("failed to new config err: %v", err) return nil, err } return kv, nil } func TestNew(t *testing.T) { ctx := context.Background() kv, err := InstallEtcd(ctx) if err != nil { t.Errorf("failed to new config err: %v", err) return } _ = kv kv.Lock(ctx, etcd_.WithLockKey("/kay/lock"), etcd_.WithLockTTL(15*time.Second)) kv.Lock(ctx, etcd_.WithLockKey("/kay/lock1"), etcd_.WithLockTTL(15*time.Second)) time.Sleep(20 * time.Second) // only unlock the latest lock /kay/lock1 kv.Unlock(ctx) kv.TxPipelined(ctx, nil, []clientv3.Op{clientv3.OpPut("foo", "foo_new_value")}, nil) /* go func() { t.Logf("before lock by routine 1") kv.Lock(ctx, "kay/lock", 15*time.Second) t.Logf("after lock by routine 1") }() */ select {} } func TestTxPipelined(t *testing.T) { ctx := context.Background() kv, err := InstallEtcd(ctx) if err != nil { t.Errorf("failed to new config err: %v", err) return } kv.TxPipelined(ctx, nil, []clientv3.Op{clientv3.OpPut("foo", "foo_new_value")}, nil) } ================================================ FILE: pkg/discovery/etcd/etcd_type.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 etcd import ( "sync/atomic" clientv3 "go.etcd.io/etcd/client/v3" ) type ETCDKV atomic.Value //check type ETCDKV* whether to implement interface of atomic.Value //var _ atomic.Value = (*ETCDKV)(nil) //check type ETCDKV whether to implement interface of atomic.Value //var _ atomic.Value = ETCDKV{} func (m *ETCDKV) Store(value *clientv3.Client) { (*atomic.Value)(m).Store(value) } func (m *ETCDKV) Load() *clientv3.Client { value := (*atomic.Value)(m).Load() if value == nil { return nil } return value.(*clientv3.Client) } ================================================ FILE: pkg/discovery/go.mod ================================================ module github.com/kaydxh/golang/pkg/discovery go 1.25.3 replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf require ( github.com/hashicorp/consul/api v1.33.0 github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/kaydxh/golang/pkg/viper v0.0.0-00010101000000-000000000000 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 go.etcd.io/etcd/api/v3 v3.6.0-alpha.0 go.etcd.io/etcd/client/v3 v3.6.0-alpha.0 go.uber.org/atomic v1.11.0 google.golang.org/protobuf v1.36.10 ) require ( github.com/armon/go-metrics v0.4.1 // indirect github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/coreos/go-semver v0.3.1 // indirect github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/fatih/color v1.16.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.28.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/google/btree v1.1.3 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-rootcerts v1.0.2 // indirect github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/hashicorp/serf v0.10.1 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.etcd.io/etcd/client/pkg/v3 v3.6.6 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) ================================================ FILE: pkg/discovery/go.sum ================================================ github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/hashicorp/consul/api v1.33.0 h1:MnFUzN1Bo6YDGi/EsRLbVNgA4pyCymmcswrE5j4OHBM= github.com/hashicorp/consul/api v1.33.0/go.mod h1:vLz2I/bqqCYiG0qRHGerComvbwSWKswc8rRFtnYBrIw= github.com/hashicorp/consul/sdk v0.17.0 h1:N/JigV6y1yEMfTIhXoW0DXUecM2grQnFuRpY7PcLHLI= github.com/hashicorp/consul/sdk v0.17.0/go.mod h1:8dgIhY6VlPUprRH7o7UenVuFEgq017qUn3k9wS5mCt4= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c= github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-msgpack v0.5.5 h1:i9R9JSrqIz0QVLz3sz+i3YJdT7TTSLcfLLzJi9aZTuI= github.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= github.com/hashicorp/go-sockaddr v1.0.2 h1:ztczhD1jLxIRjVejw8gFomI1BQZOe2WoVOu0SyteCQc= github.com/hashicorp/go-sockaddr v1.0.2/go.mod h1:rB4wwRAUzs07qva3c5SdrY/NEtAUjGlgmH/UkBUC97A= github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.1 h1:zEfKbn2+PDgroKdiOzqiE8rsmLqU2uwi5PB5pBJ3TkI= github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/YAJqrc= github.com/hashicorp/memberlist v0.5.0 h1:EtYPN8DpAURiapus508I4n9CzHs2W+8NZGbmmR/prTM= github.com/hashicorp/memberlist v0.5.0/go.mod h1:yvyXLpo0QaGE59Y7hDTsTzDD25JYBZ4mHgHUZ8lrOI0= github.com/hashicorp/serf v0.10.1 h1:Z1H2J60yRKvfDYAOZLd2MU0ND4AH/WDz7xYHDWQsIPY= github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfEvMqbG+4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= github.com/miekg/dns v1.1.41 h1:WMszZWJG0XmzbK9FEmzH2TVcqYzFesusSIB41b8KHxY= github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= go.etcd.io/etcd/api/v3 v3.6.0-alpha.0 h1:se+XckWlVTTfwjZSsAZJ2zGPzmIMq3j7fKBCmHoB9UA= go.etcd.io/etcd/api/v3 v3.6.0-alpha.0/go.mod h1:z13pg39zewDLZeXIKeM0xELOeFKcqjLocfwl5M820+w= go.etcd.io/etcd/client/pkg/v3 v3.6.6 h1:uoqgzSOv2H9KlIF5O1Lsd8sW+eMLuV6wzE3q5GJGQNs= go.etcd.io/etcd/client/pkg/v3 v3.6.6/go.mod h1:YngfUVmvsvOJ2rRgStIyHsKtOt9SZI2aBJrZiWJhCbI= go.etcd.io/etcd/client/v3 v3.6.0-alpha.0 h1:hHaJ8CvTPJ9iv7xPz3G0gxt3csEqJW8evgty/kYICwo= go.etcd.io/etcd/client/v3 v3.6.0-alpha.0/go.mod h1:a9JuChoQBDnw7WclHYBYCtTOIC12Wwj+Fw0LX4TI/Gs= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0= golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= ================================================ FILE: pkg/file-cleanup/config.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filecleanup import ( "context" "github.com/go-playground/validator/v10" disk_ "github.com/kaydxh/golang/pkg/file-cleanup/disk" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) // Config ... type Config struct { Proto disk_.DiskCleaner Validator *validator.Validate opts struct { // If set, overrides params below viper *viper.Viper diskOptions []disk_.DiskCleanerConfigOption } } type completedConfig struct { *Config completeError error } // CompletedConfig ... type CompletedConfig struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig } func (c *completedConfig) New(ctx context.Context) (*disk_.DiskCleanerSerivce, error) { logrus.Infof("Installing DiskCleanerSerivce") if c.completeError != nil { return nil, c.completeError } if !c.Proto.GetEnabled() { return nil, nil } rs, err := c.install(ctx) if err != nil { return nil, err } logrus.Infof("Installed Crontab") return rs, nil } func (c *completedConfig) install(ctx context.Context) (*disk_.DiskCleanerSerivce, error) { opts := []disk_.DiskCleanerConfigOption{ disk_.WithDiskCheckInterval(c.Proto.GetCheckInterval().AsDuration()), disk_.WithDiskBaseExpired(c.Proto.GetBaseExpired().AsDuration()), disk_.WithDiskMinExpired(c.Proto.GetMinExpired().AsDuration()), } opts = append(opts, c.opts.diskOptions...) return disk_.NewDiskCleanerSerivce( c.Proto.GetDiskUsage(), c.Proto.GetPaths(), c.Proto.GetExts(), opts..., ) } // Validate checks Config. func (c *completedConfig) Validate() error { return c.Validator.Struct(c) } // Complete fills in any fields not set that are required to have valid data and can be derived // from other fields. If you're going to `ApplyOptions`, do that first. It's mutating the receiver. func (c *Config) Complete(options ...ConfigOption) CompletedConfig { err := c.loadViper() if err != nil { return CompletedConfig{&completedConfig{ Config: c, completeError: err, }} } c.ApplyOptions(options...) return CompletedConfig{&completedConfig{Config: c}} } func (c *Config) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, &c.Proto) } return nil } // NewConfig returns a Config struct with the default values func NewConfig(options ...ConfigOption) *Config { c := &Config{} c.ApplyOptions(options...) return c } ================================================ FILE: pkg/file-cleanup/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filecleanup import ( disk_ "github.com/kaydxh/golang/pkg/file-cleanup/disk" "github.com/spf13/viper" ) func WithViper(v *viper.Viper) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.viper = v }) } func WithDiskUsageCallBack(f func(diskPath string, diskUsage float32)) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.diskOptions = append(c.opts.diskOptions, disk_.WithDiskUsageCallBack(f)) }) } func WithCleanPostCallBack(f func(file string, err error)) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.diskOptions = append(c.opts.diskOptions, disk_.WithCleanPostCallBack(f)) }) } ================================================ FILE: pkg/file-cleanup/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filecleanup // A ConfigOption sets options. type ConfigOption interface { apply(*Config) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption struct{} func (EmptyConfigOption) apply(*Config) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc func(*Config) func (f ConfigOptionFunc) apply(do *Config) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault() ConfigOption { return ConfigOptionFunc(func(*Config) { // nothing to change }) } func (o *Config) ApplyOptions(options ...ConfigOption) *Config { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/file-cleanup/disk/disk_cleaner.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 disk import ( "context" "fmt" "os" "path/filepath" "sync" "time" "github.com/kaydxh/golang/go/errors" errors_ "github.com/kaydxh/golang/go/errors" filepath_ "github.com/kaydxh/golang/go/path/filepath" strings_ "github.com/kaydxh/golang/go/strings" syscall_ "github.com/kaydxh/golang/go/syscall" time_ "github.com/kaydxh/golang/go/time" "github.com/sirupsen/logrus" "go.uber.org/atomic" ) var ( workDir string ) func init() { workDir, _ = os.Getwd() } const ( DefaultCheckInterval time.Duration = time.Minute DefaultbaseExpired time.Duration = 72 * time.Hour DefalutRandomizationFactor = 0.1 DefalutMultiplier = 0.8 DefalutMinInterval = time.Minute ) type DiskCleanerConfig struct { checkInterval time.Duration baseExpired time.Duration minExpired time.Duration diskUsageCallBack func(diskPath string, diskUsage float32) cleanPostCallBack func(file string, err error) } // DiskCleanerSerivce ... type DiskCleanerSerivce struct { // path:ExponentialBackOffMap epoByPath time_.ExponentialBackOffMap exts []string //0-100 diskUsage float32 inShutdown atomic.Bool // true when when server is in shutdown opts DiskCleanerConfig mu sync.Mutex cancel func() } func checkAndCanoicalzePaths(paths ...string) ([]string, bool) { var canPaths []string for _, path := range paths { absPath, err := filepath_.CanonicalizePath(path) if err != nil { fmt.Printf("err: %v\n", err) return nil, false } if absPath == "" || absPath == "/" || absPath == workDir { return nil, false } canPaths = append(canPaths, absPath) } return canPaths, true } // NewDiskCleanerSerivce ... func NewDiskCleanerSerivce( diskUsage float32, paths []string, exts []string, opts ...DiskCleanerConfigOption, ) (*DiskCleanerSerivce, error) { canPaths, ok := checkAndCanoicalzePaths(paths...) if !ok { return nil, fmt.Errorf("invalid paths for disk cheaner") } if diskUsage < 0 { diskUsage = 0 } if diskUsage > 100 { diskUsage = 100 } if len(exts) == 0 { return nil, fmt.Errorf("invalid exts for disk cleaner") } s := &DiskCleanerSerivce{ diskUsage: diskUsage, exts: exts, } s.opts.ApplyOptions(opts...) if s.opts.checkInterval == 0 { s.opts.checkInterval = DefaultCheckInterval } if s.opts.minExpired == 0 { s.opts.minExpired = DefalutMinInterval } if s.opts.baseExpired == 0 { s.opts.baseExpired = DefaultbaseExpired } for _, path := range canPaths { exp := time_.NewExponentialBackOff( time_.WithExponentialBackOffOptionInitialInterval(s.opts.baseExpired), time_.WithExponentialBackOffOptionRandomizationFactor(DefalutRandomizationFactor), time_.WithExponentialBackOffOptionMultiplier(DefalutMultiplier), time_.WithExponentialBackOffOptionMaxInterval(s.opts.baseExpired), time_.WithExponentialBackOffOptionMinInterval(s.opts.minExpired), time_.WithExponentialBackOffOptionMaxElapsedTime(0), ) s.epoByPath.Store(path, *exp) } fmt.Printf("s: %+v\n", s) return s, nil } func (s *DiskCleanerSerivce) getLogger() *logrus.Entry { return logrus.WithField("module", "DiskCleaner") } // Run will initialize the backend. It must not block, but may run go routines in the background. func (s *DiskCleanerSerivce) Run(ctx context.Context) error { logger := s.getLogger() logger.Infoln("DiskCleaner Run") if s.inShutdown.Load() { logger.Infoln("DiskCleaner Shutdown") return fmt.Errorf("server closed") } go func() { errors.HandleError(s.Serve(ctx)) }() return nil } // Serve ... func (s *DiskCleanerSerivce) Serve(ctx context.Context) error { logger := s.getLogger() logger.Infoln("DiskCleaner Serve") if s.inShutdown.Load() { logger.Infoln("DiskCleaner Shutdown") return fmt.Errorf("server closed") } defer s.inShutdown.Store(true) ctx, cancel := context.WithCancel(ctx) defer cancel() s.mu.Lock() s.cancel = cancel s.mu.Unlock() time_.UntilWithContxt(ctx, func(ctx context.Context) error { err := s.clean(ctx) if err != nil { logger.WithError(err).Errorf("failed to clean") return err } return nil }, s.opts.checkInterval) if err := ctx.Err(); err != nil { logger.WithError(err).Errorf("stopped checking") return err } logger.Info("stopped checking") return nil } func (s *DiskCleanerSerivce) clean(ctx context.Context) error { var ( wg sync.WaitGroup errs []error ) logger := s.getLogger() s.epoByPath.Range(func(path string, ebo time_.ExponentialBackOff) bool { wg.Add(1) go func(diskPath string, ebo time_.ExponentialBackOff) { defer wg.Done() du, err := syscall_.NewDiskUsage(diskPath) if err != nil { s.mu.Lock() errs = append(errs, err) s.mu.Unlock() return } if s.opts.diskUsageCallBack != nil { s.opts.diskUsageCallBack(diskPath, du.Usage()) } if du.Usage() >= s.diskUsage { //clean logger.Infof( "disk[%v] usage over %v, file expired: %v, start to clean", diskPath, s.diskUsage, ebo.GetCurrentInterval(), ) actualExpired, _ := ebo.NextBackOff() filepath.Walk(diskPath, func(filePath string, info os.FileInfo, err error) error { if !info.IsDir() { if strings_.SliceContainsCaseInSensitive(s.exts, filepath.Ext(filePath)) { now := time.Now() if now.Sub(info.ModTime()) > actualExpired { logger.Infof( "delete file %v expired[%v], modify time: %v, now: %v", filePath, actualExpired, info.ModTime(), now, ) err = os.Remove(filePath) if s.opts.cleanPostCallBack != nil { s.opts.cleanPostCallBack(filePath, err) } } } } return nil }) } else { // reset expired Time ebo.Reset() logger.Debugf("reset disk path: %v expired time: %v", diskPath, ebo.GetCurrentInterval()) } s.epoByPath.Store(diskPath, ebo) }(path, ebo) return true }) wg.Wait() return errors_.NewAggregate(errs) } // Shutdown ... func (s *DiskCleanerSerivce) Shutdown() { s.inShutdown.Store(true) s.mu.Lock() defer s.mu.Unlock() if s.cancel != nil { s.cancel() } } ================================================ FILE: pkg/file-cleanup/disk/disk_cleaner.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 disk import ( "time" ) func WithDiskCheckInterval(interval time.Duration) DiskCleanerConfigOption { return DiskCleanerConfigOptionFunc(func(c *DiskCleanerConfig) { c.checkInterval = interval }) } func WithDiskBaseExpired(expired time.Duration) DiskCleanerConfigOption { return DiskCleanerConfigOptionFunc(func(c *DiskCleanerConfig) { c.baseExpired = expired }) } func WithDiskMinExpired(expired time.Duration) DiskCleanerConfigOption { return DiskCleanerConfigOptionFunc(func(c *DiskCleanerConfig) { c.minExpired = expired }) } func WithDiskUsageCallBack(f func(diskPath string, diskUsage float32)) DiskCleanerConfigOption { return DiskCleanerConfigOptionFunc(func(c *DiskCleanerConfig) { c.diskUsageCallBack = f }) } func WithCleanPostCallBack(f func(file string, err error)) DiskCleanerConfigOption { return DiskCleanerConfigOptionFunc(func(c *DiskCleanerConfig) { c.cleanPostCallBack = f }) } ================================================ FILE: pkg/file-cleanup/disk/disk_cleaner.pb.go ================================================ /* *Copyright (c) 2022, kaydxh * *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. */ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 // protoc v3.13.0 // source: pkg/file-cleanup/disk/disk_cleaner.proto package disk import ( duration "github.com/golang/protobuf/ptypes/duration" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type DiskCleaner struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` // disk usage >= disk_usage, start to clean file, 0 means nerver clean, range // 0-100 DiskUsage float32 `protobuf:"fixed32,2,opt,name=disk_usage,json=diskUsage,proto3" json:"disk_usage,omitempty"` // clearn paths Paths []string `protobuf:"bytes,3,rep,name=paths,proto3" json:"paths,omitempty"` // ext Exts []string `protobuf:"bytes,4,rep,name=exts,proto3" json:"exts,omitempty"` CheckInterval *duration.Duration `protobuf:"bytes,5,opt,name=check_interval,json=checkInterval,proto3" json:"check_interval,omitempty"` BaseExpired *duration.Duration `protobuf:"bytes,6,opt,name=base_expired,json=baseExpired,proto3" json:"base_expired,omitempty"` MinExpired *duration.Duration `protobuf:"bytes,7,opt,name=min_expired,json=minExpired,proto3" json:"min_expired,omitempty"` } func (x *DiskCleaner) Reset() { *x = DiskCleaner{} if protoimpl.UnsafeEnabled { mi := &file_pkg_file_cleanup_disk_disk_cleaner_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DiskCleaner) String() string { return protoimpl.X.MessageStringOf(x) } func (*DiskCleaner) ProtoMessage() {} func (x *DiskCleaner) ProtoReflect() protoreflect.Message { mi := &file_pkg_file_cleanup_disk_disk_cleaner_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DiskCleaner.ProtoReflect.Descriptor instead. func (*DiskCleaner) Descriptor() ([]byte, []int) { return file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDescGZIP(), []int{0} } func (x *DiskCleaner) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *DiskCleaner) GetDiskUsage() float32 { if x != nil { return x.DiskUsage } return 0 } func (x *DiskCleaner) GetPaths() []string { if x != nil { return x.Paths } return nil } func (x *DiskCleaner) GetExts() []string { if x != nil { return x.Exts } return nil } func (x *DiskCleaner) GetCheckInterval() *duration.Duration { if x != nil { return x.CheckInterval } return nil } func (x *DiskCleaner) GetBaseExpired() *duration.Duration { if x != nil { return x.BaseExpired } return nil } func (x *DiskCleaner) GetMinExpired() *duration.Duration { if x != nil { return x.MinExpired } return nil } var File_pkg_file_cleanup_disk_disk_cleaner_proto protoreflect.FileDescriptor var file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDesc = []byte{ 0x0a, 0x28, 0x70, 0x6b, 0x67, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x63, 0x6c, 0x65, 0x61, 0x6e, 0x75, 0x70, 0x2f, 0x64, 0x69, 0x73, 0x6b, 0x2f, 0x64, 0x69, 0x73, 0x6b, 0x5f, 0x63, 0x6c, 0x65, 0x61, 0x6e, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x17, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x63, 0x6c, 0x65, 0x61, 0x6e, 0x75, 0x70, 0x2e, 0x64, 0x69, 0x73, 0x6b, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xac, 0x02, 0x0a, 0x0b, 0x44, 0x69, 0x73, 0x6b, 0x43, 0x6c, 0x65, 0x61, 0x6e, 0x65, 0x72, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x64, 0x69, 0x73, 0x6b, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x02, 0x52, 0x09, 0x64, 0x69, 0x73, 0x6b, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, 0x74, 0x68, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, 0x52, 0x05, 0x70, 0x61, 0x74, 0x68, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x65, 0x78, 0x74, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x04, 0x65, 0x78, 0x74, 0x73, 0x12, 0x40, 0x0a, 0x0e, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x3c, 0x0a, 0x0c, 0x62, 0x61, 0x73, 0x65, 0x5f, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x62, 0x61, 0x73, 0x65, 0x45, 0x78, 0x70, 0x69, 0x72, 0x65, 0x64, 0x12, 0x3a, 0x0a, 0x0b, 0x6d, 0x69, 0x6e, 0x5f, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x64, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0a, 0x6d, 0x69, 0x6e, 0x45, 0x78, 0x70, 0x69, 0x72, 0x65, 0x64, 0x42, 0x30, 0x5a, 0x2e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x63, 0x6c, 0x65, 0x61, 0x6e, 0x75, 0x70, 0x2e, 0x64, 0x69, 0x73, 0x6b, 0x3b, 0x64, 0x69, 0x73, 0x6b, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDescOnce sync.Once file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDescData = file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDesc ) func file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDescGZIP() []byte { file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDescOnce.Do(func() { file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDescData) }) return file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDescData } var file_pkg_file_cleanup_disk_disk_cleaner_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_pkg_file_cleanup_disk_disk_cleaner_proto_goTypes = []interface{}{ (*DiskCleaner)(nil), // 0: go.pkg.filecleanup.disk.DiskCleaner (*duration.Duration)(nil), // 1: google.protobuf.Duration } var file_pkg_file_cleanup_disk_disk_cleaner_proto_depIdxs = []int32{ 1, // 0: go.pkg.filecleanup.disk.DiskCleaner.check_interval:type_name -> google.protobuf.Duration 1, // 1: go.pkg.filecleanup.disk.DiskCleaner.base_expired:type_name -> google.protobuf.Duration 1, // 2: go.pkg.filecleanup.disk.DiskCleaner.min_expired:type_name -> google.protobuf.Duration 3, // [3:3] is the sub-list for method output_type 3, // [3:3] is the sub-list for method input_type 3, // [3:3] is the sub-list for extension type_name 3, // [3:3] is the sub-list for extension extendee 0, // [0:3] is the sub-list for field type_name } func init() { file_pkg_file_cleanup_disk_disk_cleaner_proto_init() } func file_pkg_file_cleanup_disk_disk_cleaner_proto_init() { if File_pkg_file_cleanup_disk_disk_cleaner_proto != nil { return } if !protoimpl.UnsafeEnabled { file_pkg_file_cleanup_disk_disk_cleaner_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DiskCleaner); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_pkg_file_cleanup_disk_disk_cleaner_proto_goTypes, DependencyIndexes: file_pkg_file_cleanup_disk_disk_cleaner_proto_depIdxs, MessageInfos: file_pkg_file_cleanup_disk_disk_cleaner_proto_msgTypes, }.Build() File_pkg_file_cleanup_disk_disk_cleaner_proto = out.File file_pkg_file_cleanup_disk_disk_cleaner_proto_rawDesc = nil file_pkg_file_cleanup_disk_disk_cleaner_proto_goTypes = nil file_pkg_file_cleanup_disk_disk_cleaner_proto_depIdxs = nil } ================================================ FILE: pkg/file-cleanup/disk/disk_cleaner.proto ================================================ syntax = "proto3"; package go.pkg.filecleanup.disk; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/go.pkg.filecleanup.disk;disk"; message DiskCleaner { bool enabled = 1; // disk usage >= disk_usage, start to clean file, 0 means nerver clean, range // 0-100 float disk_usage = 2; // clearn paths repeated string paths = 3; // ext repeated string exts = 4; google.protobuf.Duration check_interval = 5; google.protobuf.Duration base_expired = 6; google.protobuf.Duration min_expired = 7; } ================================================ FILE: pkg/file-cleanup/disk/disk_cleaner_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 disk // A DiskCleanerConfigOption sets options. type DiskCleanerConfigOption interface { apply(*DiskCleanerConfig) } // EmptyDiskCleanerConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyDiskCleanerConfigOption struct{} func (EmptyDiskCleanerConfigOption) apply(*DiskCleanerConfig) {} // DiskCleanerConfigOptionFunc wraps a function that modifies Client into an // implementation of the DiskCleanerConfigOption interface. type DiskCleanerConfigOptionFunc func(*DiskCleanerConfig) func (f DiskCleanerConfigOptionFunc) apply(do *DiskCleanerConfig) { f(do) } // sample code for option, default for nothing to change func _DiskCleanerConfigOptionWithDefault() DiskCleanerConfigOption { return DiskCleanerConfigOptionFunc(func(*DiskCleanerConfig) { // nothing to change }) } func (o *DiskCleanerConfig) ApplyOptions(options ...DiskCleanerConfigOption) *DiskCleanerConfig { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/file-cleanup/disk_cleaner_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filecleanup_test import ( "context" "fmt" "testing" "time" viper_ "github.com/kaydxh/golang/pkg/viper" filecleanup_ "github.com/kaydxh/golang/pkg/file-cleanup" ) func diskUsageCallBack(diskPath string, diskUsage float32) { fmt.Printf("diskUsageCallBack diskPath: %v, diskUsage: %v\n", diskPath, diskUsage) } func TestDiskCleanerSerivce(t *testing.T) { cfgFile := "./diskcleaner.yaml" config := filecleanup_.NewConfig( filecleanup_.WithViper(viper_.GetViper(cfgFile, "diskcleaner")), filecleanup_.WithDiskUsageCallBack(diskUsageCallBack), ) s, err := config.Complete().New(context.Background()) if err != nil { t.Fatalf("failed to new config err: %v", err) } s.Run(context.Background()) time.Sleep(1 * time.Minute) } ================================================ FILE: pkg/file-cleanup/diskcleaner.yaml ================================================ diskcleaner: enabled: true disk_usage: 85 paths: [ "/data" ] exts: [".jpg"] check_interval: 60s base_expired : 518400s # 144h min_expired: 60s ================================================ FILE: pkg/file-cleanup/file_cleaner.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filecleanup import ( "os" "sort" "time" errors_ "github.com/kaydxh/golang/go/errors" filepath_ "github.com/kaydxh/golang/go/path/filepath" ) type FileCleaner struct { //filedir string //pattern string //maxAge is the maximum number of time to retain old files, 0 is unlimited maxAge time.Duration //maxCount is the maximum number to retain old files, 0 is unlimited maxCount int64 } func FileCleanup(pattern string, options ...FileCleanerOption) error { var cleaner FileCleaner cleaner.ApplyOptions(options...) matches, err := filepath_.Glob(pattern) if err != nil { return err } now := time.Now() removeMatches := make([]string, 0, len(matches)) for _, path := range matches { fi, err := os.Stat(path) if err != nil { continue } // maxAge 0 is unlimited if cleaner.maxAge <= 0 { continue } if now.Sub(fi.ModTime()) < cleaner.maxAge { continue } removeMatches = append(removeMatches, path) } if cleaner.maxCount > 0 { if cleaner.maxCount < int64(len(matches)) { removeCount := len(matches) - int(cleaner.maxCount) - len(removeMatches) if removeCount > 0 { sort.Sort(RotatedFiles(matches)) removeMatches = append( removeMatches, matches[len(removeMatches):len(removeMatches)+removeCount]..., ) } } } //clean var errs []error for _, file := range removeMatches { err = os.Remove(file) if err != nil { errs = append(errs, err) } } return errors_.NewAggregate(errs) } type RotatedFiles []string func (f RotatedFiles) Len() int { return len(f) } func (f RotatedFiles) Swap(i, j int) { f[i], f[j] = f[j], f[i] } func (f RotatedFiles) Less(i, j int) bool { fi, err := os.Stat(f[i]) if err != nil { return false } fj, err := os.Stat(f[j]) if err != nil { return false } if fi.ModTime().Equal(fj.ModTime()) { if len(f[i]) == len(f[j]) { return f[i] < f[j] } return len(f[i]) < len(f[j]) // foo.9 < foo.10 } return fi.ModTime().Before(fj.ModTime()) } ================================================ FILE: pkg/file-cleanup/file_cleaner.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filecleanup import ( "time" ) func WithMaxAge(maxAge time.Duration) FileCleanerOption { return FileCleanerOptionFunc(func(c *FileCleaner) { c.maxAge = maxAge }) } func WithMaxCount(maxCount int64) FileCleanerOption { return FileCleanerOptionFunc(func(c *FileCleaner) { c.maxCount = maxCount }) } ================================================ FILE: pkg/file-cleanup/file_cleaner_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filecleanup // A FileCleanerOption sets options. type FileCleanerOption interface { apply(*FileCleaner) } // EmptyFileCleanerOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyFileCleanerOption struct{} func (EmptyFileCleanerOption) apply(*FileCleaner) {} // FileCleanerOptionFunc wraps a function that modifies Client into an // implementation of the FileCleanerOption interface. type FileCleanerOptionFunc func(*FileCleaner) func (f FileCleanerOptionFunc) apply(do *FileCleaner) { f(do) } // sample code for option, default for nothing to change func _FileCleanerOptionWithDefault() FileCleanerOption { return FileCleanerOptionFunc(func(*FileCleaner) { // nothing to change }) } func (o *FileCleaner) ApplyOptions(options ...FileCleanerOption) *FileCleaner { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/file-cleanup/file_cleaner_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filecleanup_test import ( "testing" "time" filecleanup_ "github.com/kaydxh/golang/pkg/file-cleanup" ) func TestFileCleanupWithMaxAge(t *testing.T) { err := filecleanup_.FileCleanup( "/Users/kayxhding/workspace/studyspace/git-kayxhding/github.com/kaydxh/golang/pkg/file-cleanup/log/*", filecleanup_.WithMaxAge(time.Second), ) if err != nil { t.Fatalf("faild to FileCleanup, err: %v", err) } } ================================================ FILE: pkg/file-cleanup/go.mod ================================================ module github.com/kaydxh/golang/pkg/file-cleanup go 1.24.0 replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf require ( github.com/go-playground/validator/v10 v10.28.0 github.com/golang/protobuf v1.5.4 github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/kaydxh/golang/pkg/viper v0.0.0-20251125160242-e06b25c89946 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.21.0 go.uber.org/atomic v1.11.0 google.golang.org/protobuf v1.36.10 ) require ( github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect ) ================================================ FILE: pkg/file-cleanup/go.sum ================================================ github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= ================================================ FILE: pkg/file-rotate/go.mod ================================================ module github.com/kaydxh/golang/pkg/file-rotate go 1.24.0 replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf replace github.com/kaydxh/golang/pkg/file-cleanup => ../file-cleanup require ( github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/kaydxh/golang/pkg/file-cleanup v0.0.0-00010101000000-000000000000 github.com/sirupsen/logrus v1.9.3 ) require ( github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.28.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/kaydxh/golang/pkg/viper v0.0.0-20251125160242-e06b25c89946 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/spf13/viper v1.21.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect google.golang.org/protobuf v1.36.10 // indirect ) ================================================ FILE: pkg/file-rotate/go.sum ================================================ github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= ================================================ FILE: pkg/file-rotate/rotate_file.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 rotatefile import ( "context" "fmt" "io" "os" "path/filepath" "regexp" "sort" "strconv" "strings" "sync" "time" os_ "github.com/kaydxh/golang/go/os" filepath_ "github.com/kaydxh/golang/go/path/filepath" time_ "github.com/kaydxh/golang/go/time" cleanup_ "github.com/kaydxh/golang/pkg/file-cleanup" ) type EventCallbackFunc func(ctx context.Context, path string) type RotateFiler struct { file *os.File filedir string curFilepath string seq uint64 linkpath string mu sync.Mutex opts struct { prefixName string fileTimeLayout string //default "20060102150405" ,take effect if rotateInterval > 0 subfixName string //maxAge is the maximum number of time to retain old files, 0 is unlimited maxAge time.Duration //maxCount is the maximum number to retain old files, 0 is unlimited maxCount int64 //rotate file when file size larger than rotateSize rotateSize int64 //rotate file in rotateInterval rotateInterval time.Duration syncInterval time.Duration rotateCallbackFunc EventCallbackFunc } } func NewRotateFiler(filedir string, options ...RotateFilerOption) (*RotateFiler, error) { r := &RotateFiler{ filedir: filedir, } r.ApplyOptions(options...) if r.linkpath == "" { r.linkpath = filepath.Base(os.Args[0]) + ".log" } // if need rotate file with rotateInterval, set default timelayout if r.opts.rotateInterval > 0 { if r.opts.fileTimeLayout == "" { r.opts.fileTimeLayout = time_.ShortTimeFormat } } if r.opts.rotateCallbackFunc != nil { if r.opts.syncInterval == 0 { r.opts.syncInterval = 30 * time.Second } go r.watch() } return r, nil } // /data/log/1%%%AA20160304 -> /data/log/1*A20160304* func globFromFileTimeLayout(filePath string) string { regexps := []*regexp.Regexp{ regexp.MustCompile(`%[%+A-Za-z]`), regexp.MustCompile(`\*+`), } for _, re := range regexps { filePath = re.ReplaceAllString(filePath, "*") } return filePath + "*" } func (f *RotateFiler) Write(p []byte) (file *os.File, n int, err error) { f.mu.Lock() defer f.mu.Unlock() out, err := f.getWriterNolock(int64(len(p))) if err != nil { return nil, 0, err } n, err = out.Write(p) return f.file, n, err } func (f *RotateFiler) WriteBytesLine(p [][]byte) (file *os.File, n int, err error) { var data []byte for _, d := range p { data = append(data, d...) data = append(data, '\n') } return f.Write(data) } func (f *RotateFiler) generateRotateFilename() string { if f.opts.rotateInterval > 0 { now := time.Now() return time_.TruncateToUTCString(now, f.opts.rotateInterval, f.opts.fileTimeLayout) } return "" } func (f *RotateFiler) watch() { timer := time.NewTicker(f.opts.syncInterval) defer timer.Stop() for { select { case <-timer.C: func() { f.mu.Lock() defer f.mu.Unlock() f.getWriterNolock(0) }() } } } func (f *RotateFiler) getWriterNolock(length int64) (io.Writer, error) { basename := f.generateRotateFilename() filename := f.opts.prefixName + basename + f.opts.subfixName if filename == "" { filename = "default.log" } // first rotate log file, maybe /data/logs/logs.test20210917230000.log filePath := filepath.Join(f.filedir, filename) globPath := filepath.Join(filepath.Dir(filePath), f.opts.prefixName) // current log file, maybe /data/logs/logs.test20210917230000.log.1 if f.curFilepath == "" { f.curFilepath, _ = f.getCurSeqFilename(globPath) f.seq = f.extractSeq(f.curFilepath) } // if curFilePath is different rotated time with filename, need reset curFilePath if !strings.Contains(f.curFilepath, filename) { f.curFilepath = filePath f.seq = 0 } rotated := false fi, err := os.Stat(f.curFilepath) if err != nil { if !os.IsNotExist(err) { return nil, fmt.Errorf("failed to get file info, err: %v", err) } //file is not exist, think just like rotating file rotated = true } //rotate file by size if err == nil && f.opts.rotateSize > 0 && (fi.Size()+length) > f.opts.rotateSize { f.curFilepath, err = f.generateNextSeqFilename(filePath) if err != nil { return nil, fmt.Errorf("failed to generate rotate file name by seq, err: %v", err) } rotated = true } if f.file == nil || rotated { fn, err := os_.OpenFile(f.curFilepath, true) if err != nil { return nil, fmt.Errorf("failed to create file: %v, err: %v", f.curFilepath, err) } if f.file != nil { //callback if f.opts.rotateCallbackFunc != nil { f.opts.rotateCallbackFunc(context.Background(), f.file.Name()) } f.file.Close() } f.file = fn f.seq = f.extractSeq(f.curFilepath) os_.SymLink(f.curFilepath, f.linkpath) globFile := globFromFileTimeLayout(globPath) go cleanup_.FileCleanup(globFile, cleanup_.WithMaxAge(f.opts.maxAge), cleanup_.WithMaxCount(f.opts.maxCount)) } return f.file, nil } //filename like foo foo.1 foo.2 ... func (f *RotateFiler) generateNextSeqFilename(filePath string) (string, error) { var newFilePath string seq := f.seq for { if seq == 0 { newFilePath = filePath } else { newFilePath = fmt.Sprintf("%s.%d", filePath, seq) } _, err := os.Stat(newFilePath) if os.IsNotExist(err) { f.seq = seq return newFilePath, nil } if err != nil { return "", err } //file exist, need to get next seq filename seq++ } } // globPath: log/logs.test // globFile: [log/logs.test20211008081908.log log/logs.test20211008081908.log.1 log/logs.test20211008081908.log.2] func (f *RotateFiler) getCurSeqFilename(globPath string) (string, error) { globFile := globFromFileTimeLayout(globPath) matches, err := filepath_.Glob(globFile) if err != nil { return "", err } if len(matches) == 0 { return globPath, nil } sort.Sort(cleanup_.RotatedFiles(matches)) return matches[len(matches)-1], nil } func (f *RotateFiler) extractSeq(filePath string) uint64 { if filePath == "" { return 0 } ext := filepath.Ext(filePath) if ext == "" { return 0 } seq, err := strconv.ParseUint(ext[1:], 10, 64) if err != nil { return 0 } return seq } ================================================ FILE: pkg/file-rotate/rotate_file.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 rotatefile import ( "time" ) func WithPrefixName(prefixName string) RotateFilerOption { return RotateFilerOptionFunc(func(c *RotateFiler) { c.opts.prefixName = prefixName }) } func WithFileTimeLayout(fileTimeLayout string) RotateFilerOption { return RotateFilerOptionFunc(func(c *RotateFiler) { c.opts.fileTimeLayout = fileTimeLayout }) } func WithSuffixName(subfixName string) RotateFilerOption { return RotateFilerOptionFunc(func(c *RotateFiler) { c.opts.subfixName = subfixName }) } func WithMaxAge(maxAge time.Duration) RotateFilerOption { return RotateFilerOptionFunc(func(c *RotateFiler) { c.opts.maxAge = maxAge }) } func WithMaxCount(maxCount int64) RotateFilerOption { return RotateFilerOptionFunc(func(c *RotateFiler) { c.opts.maxCount = maxCount }) } func WithRotateSize(rotateSize int64) RotateFilerOption { return RotateFilerOptionFunc(func(c *RotateFiler) { c.opts.rotateSize = rotateSize }) } func WithRotateInterval(rotateInterval time.Duration) RotateFilerOption { return RotateFilerOptionFunc(func(c *RotateFiler) { c.opts.rotateInterval = rotateInterval }) } func WithRotateCallback(callback EventCallbackFunc) RotateFilerOption { return RotateFilerOptionFunc(func(c *RotateFiler) { c.opts.rotateCallbackFunc = callback }) } ================================================ FILE: pkg/file-rotate/rotate_file_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 rotatefile // A RotateFilerOption sets options. type RotateFilerOption interface { apply(*RotateFiler) } // EmptyRotateFilerOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyRotateFilerOption struct{} func (EmptyRotateFilerOption) apply(*RotateFiler) {} // RotateFilerOptionFunc wraps a function that modifies Client into an // implementation of the RotateFilerOption interface. type RotateFilerOptionFunc func(*RotateFiler) func (f RotateFilerOptionFunc) apply(do *RotateFiler) { f(do) } // sample code for option, default for nothing to change func _RotateFilerOptionWithDefault() RotateFilerOption { return RotateFilerOptionFunc(func(*RotateFiler) { // nothing to change }) } func (o *RotateFiler) ApplyOptions(options ...RotateFilerOption) *RotateFiler { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/file-rotate/rotate_file_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 rotatefile_test import ( "context" "fmt" "os" "path/filepath" "regexp" "testing" "time" rotate_ "github.com/kaydxh/golang/pkg/file-rotate" "github.com/sirupsen/logrus" ) func getWdOrDie() string { path, err := os.Getwd() if err != nil { logrus.Fatalf("failed to get wd, err: %v", err) } return path } func TestRotateFileWithInterval(t *testing.T) { rotateFiler, _ := rotate_.NewRotateFiler( filepath.Join(getWdOrDie(), "log"), rotate_.WithRotateInterval(time.Second), rotate_.WithSuffixName(".log"), rotate_.WithPrefixName(filepath.Base(os.Args[0])), ) for i := 0; i < 10; i++ { _, n, err := rotateFiler.Write([]byte("hello word")) if err != nil { t.Errorf("faild to write, err: %v", err) } time.Sleep(1 * time.Second) t.Logf("successed to write %v bytes", n) } } func TestRotateFileWithIntervalAndSize(t *testing.T) { rotateFiler, _ := rotate_.NewRotateFiler( filepath.Join(getWdOrDie(), "log"), rotate_.WithRotateInterval(time.Hour), rotate_.WithRotateSize(15), rotate_.WithSuffixName(".log"), rotate_.WithPrefixName(filepath.Base(os.Args[0])), ) for i := 0; i < 0; i++ { _, n, err := rotateFiler.Write([]byte("hello word")) if err != nil { t.Errorf("faild to write, err: %v", err) } time.Sleep(time.Second) t.Logf("successed to write %v bytes", n) } } func TestRotateFileWithSize(t *testing.T) { rotateFiler, _ := rotate_.NewRotateFiler( filepath.Join(getWdOrDie(), "log"), rotate_.WithRotateSize(10), rotate_.WithRotateInterval(15*time.Second), rotate_.WithSuffixName(".log"), rotate_.WithPrefixName(filepath.Base(os.Args[0])), rotate_.WithRotateCallback(func(ctx context.Context, path string) { t.Logf("=======callback path: %v", path) }), ) for i := 0; i < 5; i++ { //_, n, err := rotateFiler.Write([]byte("hello word")) _, n, err := rotateFiler.WriteBytesLine([][]byte{[]byte("hello word")}) if err != nil { t.Errorf("faild to write, err: %v", err) } time.Sleep(time.Second) t.Logf("successed to write %v bytes", n) } select {} } func TestRotateMaxCount(t *testing.T) { rotateFiler, _ := rotate_.NewRotateFiler( filepath.Join(getWdOrDie(), "log"), rotate_.WithRotateSize(15), rotate_.WithMaxCount(5), rotate_.WithSuffixName(".log"), rotate_.WithPrefixName(filepath.Base(os.Args[0])), ) for i := 0; i < 10; i++ { _, n, err := rotateFiler.Write([]byte("hello word")) if err != nil { t.Errorf("faild to write, err: %v", err) } time.Sleep(time.Second) t.Logf("successed to write %v bytes", n) } } func TestRegex(t *testing.T) { var regexps = []*regexp.Regexp{ regexp.MustCompile(`%[%+A-Za-z]`), regexp.MustCompile(`\*+`), } globPattern := "1%%%AA20160304" for _, re := range regexps { globPattern = re.ReplaceAllString(globPattern, "*") fmt.Printf("re: %v , globPattern: %v\n", re, globPattern) } // return globPattern + `*` } ================================================ FILE: pkg/file-transfer/config.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filetransfer import ( "context" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) type Config struct { Proto Ft opts struct { // If set, overrides params below viper *viper.Viper } } type completedConfig struct { *Config completeError error } type CompletedConfig struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig } func (c *completedConfig) New(ctx context.Context) (*FileTransfer, error) { logrus.Infof("Installing FileTransfer") if c.completeError != nil { return nil, c.completeError } if !c.Proto.GetEnabled() { return nil, nil } rs, err := c.install(ctx) if err != nil { return nil, err } logrus.Infof("Installed FileTransfer") return rs, nil } func (c *completedConfig) install(ctx context.Context) (*FileTransfer, error) { ft := NewFileTransfer( WithDownloadTimeout(c.Proto.GetDownloadTimeout().AsDuration()), WithLoadBalanceMode(c.Proto.LoadBalanceMode), WithProxies(c.Proto.Proxies), WithRetryTimes(int(c.Proto.RetryTimes)), WithRetryInterval(c.Proto.RetryInterval.AsDuration()), ) return ft, nil } // Complete set default ServerRunOptions. func (c *Config) Complete() CompletedConfig { err := c.loadViper() if err != nil { return CompletedConfig{&completedConfig{ Config: c, completeError: err, }} } return CompletedConfig{&completedConfig{Config: c}} } func (c *Config) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, &c.Proto) } return nil } func NewConfig(options ...ConfigOption) *Config { c := &Config{} c.ApplyOptions(options...) return c } ================================================ FILE: pkg/file-transfer/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filetransfer import ( "github.com/spf13/viper" ) func WithViper(v *viper.Viper) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.viper = v }) } ================================================ FILE: pkg/file-transfer/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filetransfer // A ConfigOption sets options. type ConfigOption interface { apply(*Config) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption struct{} func (EmptyConfigOption) apply(*Config) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc func(*Config) func (f ConfigOptionFunc) apply(do *Config) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault() ConfigOption { return ConfigOptionFunc(func(*Config) { // nothing to change }) } func (o *Config) ApplyOptions(options ...ConfigOption) *Config { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/file-transfer/file.transfer.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filetransfer import ( "context" "math/rand" "time" http_ "github.com/kaydxh/golang/go/net/http" time_ "github.com/kaydxh/golang/go/time" logs_ "github.com/kaydxh/golang/pkg/logs" "go.opentelemetry.io/otel" ) type FileTransferOptions struct { // 0 means no timeout downloadTimeout time.Duration uploadTimeout time.Duration loadBalanceMode Ft_LoadBalanceMode retryTimes int // retry interval, 0 means retry immediately retryInterval time.Duration proxies []*Ft_Proxy } func defaultFileTransferOptions() FileTransferOptions { return FileTransferOptions{} } type FileTransfer struct { opts FileTransferOptions } func NewFileTransfer(opts ...FileTransferOption) *FileTransfer { ft := &FileTransfer{} ft.ApplyOptions(opts...) return ft } func (f *FileTransfer) getProxy() *Ft_Proxy { proxies := f.opts.proxies if len(proxies) == 0 { return &Ft_Proxy{} } switch f.opts.loadBalanceMode { case Ft_load_balance_mode_random: return proxies[rand.Intn(len(proxies))] default: return proxies[0] } } // short connection func (f *FileTransfer) Download(ctx context.Context, downloadUrl string) (data []byte, err error) { spanName := "Download" ctx, span := otel.Tracer("").Start(ctx, spanName) defer span.End() logger := logs_.GetLogger(ctx) logger = logger.WithField("trace_id", span.SpanContext().TraceID()).WithField("span_id", span.SpanContext().SpanID()).WithField("download_url", downloadUrl) proxy := f.getProxy() opts := []http_.ClientOption{http_.WithDisableKeepAlives(true)} if proxy.TargetHost != "" { opts = append(opts, http_.WithTargetHost(proxy.TargetHost)) } else { if proxy.ProxyUrl != "" { opts = append(opts, http_.WithProxyURL(proxy.ProxyUrl)) } if proxy.ProxyHost != "" { opts = append(opts, http_.WithProxyHost(proxy.ProxyHost)) } } opts = append(opts, http_.WithTimeout(f.opts.downloadTimeout)) err = time_.RetryWithContext(ctx, func(ctx context.Context) error { client, err := http_.NewClient(opts...) if err != nil { logger.WithError(err).Errorf("new http client err: %v", err) return err } data, err = client.Get(ctx, downloadUrl) if err != nil { logger.WithError(err).Errorf("http client get err: %v", err) return err } return nil }, f.opts.retryInterval, f.opts.retryTimes) return data, err } // short connection func (f *FileTransfer) Upload(ctx context.Context, uploadUrl string, body []byte) (data []byte, err error) { spanName := "Upload" ctx, span := otel.Tracer("").Start(ctx, spanName) defer span.End() logger := logs_.GetLogger(ctx) logger = logger.WithField("trace_id", span.SpanContext().TraceID()).WithField("span_id", span.SpanContext().SpanID()).WithField("upload_url", uploadUrl) proxy := f.getProxy() opts := []http_.ClientOption{http_.WithDisableKeepAlives(true)} if proxy.TargetHost != "" { opts = append(opts, http_.WithTargetHost(proxy.TargetHost)) } else { if proxy.ProxyUrl != "" { opts = append(opts, http_.WithProxyURL(proxy.ProxyUrl)) } if proxy.ProxyHost != "" { opts = append(opts, http_.WithProxyHost(proxy.ProxyHost)) } } opts = append(opts, http_.WithTimeout(f.opts.uploadTimeout)) err = time_.RetryWithContext(ctx, func(ctx context.Context) error { client, err := http_.NewClient(opts...) if err != nil { logger.WithError(err).Errorf("new http client err: %v", err) return err } data, err = client.Put(ctx, uploadUrl, "", nil, body) if err != nil { logger.WithError(err).Errorf("http client put err: %v", err) return err } return nil }, f.opts.retryInterval, f.opts.retryTimes) return data, err } ================================================ FILE: pkg/file-transfer/file.transfer.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filetransfer import "time" func WithDownloadTimeout(downloadTimeout time.Duration) FileTransferOption { return FileTransferOptionFunc(func(r *FileTransfer) { r.opts.downloadTimeout = downloadTimeout }) } func WithLoadBalanceMode(mode Ft_LoadBalanceMode) FileTransferOption { return FileTransferOptionFunc(func(r *FileTransfer) { r.opts.loadBalanceMode = mode }) } func WithProxies(proxies []*Ft_Proxy) FileTransferOption { return FileTransferOptionFunc(func(r *FileTransfer) { r.opts.proxies = proxies }) } func WithRetryTimes(retryTimes int) FileTransferOption { return FileTransferOptionFunc(func(r *FileTransfer) { r.opts.retryTimes = retryTimes }) } func WithRetryInterval(retryInterval time.Duration) FileTransferOption { return FileTransferOptionFunc(func(r *FileTransfer) { r.opts.retryInterval = retryInterval }) } ================================================ FILE: pkg/file-transfer/file.transfer_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filetransfer // A FileTransferOption sets options. type FileTransferOption interface { apply(*FileTransfer) } // EmptyFileTransferUrlOption does not alter the FileTransferuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyFileTransferOption struct{} func (EmptyFileTransferOption) apply(*FileTransfer) {} // FileTransferOptionFunc wraps a function that modifies FileTransfer into an // implementation of the FileTransferOption interface. type FileTransferOptionFunc func(*FileTransfer) func (f FileTransferOptionFunc) apply(do *FileTransfer) { f(do) } // sample code for option, default for nothing to change func _FileTransferOptionWithDefault() FileTransferOption { return FileTransferOptionFunc(func(*FileTransfer) { // nothing to change }) } func (o *FileTransfer) ApplyOptions(options ...FileTransferOption) *FileTransfer { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/file-transfer/file.transfer_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 filetransfer_test import ( "context" "fmt" "testing" filetransfer_ "github.com/kaydxh/golang/pkg/file-transfer" viper_ "github.com/kaydxh/golang/pkg/viper" ) func TestDownload(t *testing.T) { cfgFile := "./ft.yaml" config := filetransfer_.NewConfig(filetransfer_.WithViper(viper_.GetViper(cfgFile, "filetransfer"))) ft, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } testCases := []struct { Url string }{ { Url: "https://ai-media-1256936300.cos.ap-guangzhou.myqcloud.com/find.sh?q-sign-algorithm=sha1&q-ak=AKIDCDyve81SJuISPkMq0IukLg7tupWyoqCg&q-sign-time=1659955959;8640000001659870000&q-key-time=1659955959;8640000001659870000&q-header-list=&q-url-param-list=&q-signature=5695f17ee30c3cd2d37197c773a445eda8a70c8c", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { data, err := ft.Download(context.Background(), testCase.Url) if err != nil { t.Fatalf("failed to download: %v, got : %s", testCase.Url, err) } t.Logf("data len: %v", len(data)) t.Logf("data : %v", string(data)) }) } } func TestDownloadByProxy(t *testing.T) { cfgFile := "./ft.yaml" config := filetransfer_.NewConfig(filetransfer_.WithViper(viper_.GetViper(cfgFile, "filetransfer"))) ft, err := config.Complete().New(context.Background()) if err != nil { t.Errorf("failed to new config err: %v", err) } testCases := []struct { Url string }{ { Url: "http://quyujiaofu-new-1300074211.cos.ap-guangzhou.myqcloud.com/hk_test/480p.jpg", }, } for i, testCase := range testCases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { data, err := ft.Download(context.Background(), testCase.Url) if err != nil { t.Fatalf("failed to download: %v, got : %s", testCase.Url, err) } t.Logf("data len: %v", len(data)) t.Logf("data : %v", string(data)) }) } } ================================================ FILE: pkg/file-transfer/ft.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.13.0 // source: pkg/file-transfer/ft.proto package filetransfer import ( duration "github.com/golang/protobuf/ptypes/duration" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Ft_LoadBalanceMode int32 const ( Ft_load_balance_mode_first Ft_LoadBalanceMode = 0 Ft_load_balance_mode_random Ft_LoadBalanceMode = 1 ) // Enum value maps for Ft_LoadBalanceMode. var ( Ft_LoadBalanceMode_name = map[int32]string{ 0: "load_balance_mode_first", 1: "load_balance_mode_random", } Ft_LoadBalanceMode_value = map[string]int32{ "load_balance_mode_first": 0, "load_balance_mode_random": 1, } ) func (x Ft_LoadBalanceMode) Enum() *Ft_LoadBalanceMode { p := new(Ft_LoadBalanceMode) *p = x return p } func (x Ft_LoadBalanceMode) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Ft_LoadBalanceMode) Descriptor() protoreflect.EnumDescriptor { return file_pkg_file_transfer_ft_proto_enumTypes[0].Descriptor() } func (Ft_LoadBalanceMode) Type() protoreflect.EnumType { return &file_pkg_file_transfer_ft_proto_enumTypes[0] } func (x Ft_LoadBalanceMode) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Ft_LoadBalanceMode.Descriptor instead. func (Ft_LoadBalanceMode) EnumDescriptor() ([]byte, []int) { return file_pkg_file_transfer_ft_proto_rawDescGZIP(), []int{0, 0} } type Ft struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` DownloadTimeout *duration.Duration `protobuf:"bytes,2,opt,name=download_timeout,json=downloadTimeout,proto3" json:"download_timeout,omitempty"` UploadTimeout *duration.Duration `protobuf:"bytes,3,opt,name=upload_timeout,json=uploadTimeout,proto3" json:"upload_timeout,omitempty"` RetryTimes uint32 `protobuf:"varint,4,opt,name=retry_times,json=retryTimes,proto3" json:"retry_times,omitempty"` RetryInterval *duration.Duration `protobuf:"bytes,5,opt,name=retry_interval,json=retryInterval,proto3" json:"retry_interval,omitempty"` // 当有多个代理地址时,代理模式, use proxy mode LoadBalanceMode Ft_LoadBalanceMode `protobuf:"varint,10,opt,name=load_balance_mode,json=loadBalanceMode,proto3,enum=go.pkg.filetransfer.Ft_LoadBalanceMode" json:"load_balance_mode,omitempty"` Proxies []*Ft_Proxy `protobuf:"bytes,11,rep,name=proxies,proto3" json:"proxies,omitempty"` } func (x *Ft) Reset() { *x = Ft{} if protoimpl.UnsafeEnabled { mi := &file_pkg_file_transfer_ft_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Ft) String() string { return protoimpl.X.MessageStringOf(x) } func (*Ft) ProtoMessage() {} func (x *Ft) ProtoReflect() protoreflect.Message { mi := &file_pkg_file_transfer_ft_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Ft.ProtoReflect.Descriptor instead. func (*Ft) Descriptor() ([]byte, []int) { return file_pkg_file_transfer_ft_proto_rawDescGZIP(), []int{0} } func (x *Ft) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *Ft) GetDownloadTimeout() *duration.Duration { if x != nil { return x.DownloadTimeout } return nil } func (x *Ft) GetUploadTimeout() *duration.Duration { if x != nil { return x.UploadTimeout } return nil } func (x *Ft) GetRetryTimes() uint32 { if x != nil { return x.RetryTimes } return 0 } func (x *Ft) GetRetryInterval() *duration.Duration { if x != nil { return x.RetryInterval } return nil } func (x *Ft) GetLoadBalanceMode() Ft_LoadBalanceMode { if x != nil { return x.LoadBalanceMode } return Ft_load_balance_mode_first } func (x *Ft) GetProxies() []*Ft_Proxy { if x != nil { return x.Proxies } return nil } type Ft_Proxy struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // target_addr和target_url都设置值的情况下,优先使用target_addr // reset dns to target_addr in url, TargetHost string `protobuf:"bytes,1,opt,name=target_host,json=targetHost,proto3" json:"target_host,omitempty"` // reset url to target url ProxyUrl string `protobuf:"bytes,2,opt,name=proxy_url,json=proxyUrl,proto3" json:"proxy_url,omitempty"` ProxyHost string `protobuf:"bytes,3,opt,name=proxy_host,json=proxyHost,proto3" json:"proxy_host,omitempty"` } func (x *Ft_Proxy) Reset() { *x = Ft_Proxy{} if protoimpl.UnsafeEnabled { mi := &file_pkg_file_transfer_ft_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Ft_Proxy) String() string { return protoimpl.X.MessageStringOf(x) } func (*Ft_Proxy) ProtoMessage() {} func (x *Ft_Proxy) ProtoReflect() protoreflect.Message { mi := &file_pkg_file_transfer_ft_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Ft_Proxy.ProtoReflect.Descriptor instead. func (*Ft_Proxy) Descriptor() ([]byte, []int) { return file_pkg_file_transfer_ft_proto_rawDescGZIP(), []int{0, 0} } func (x *Ft_Proxy) GetTargetHost() string { if x != nil { return x.TargetHost } return "" } func (x *Ft_Proxy) GetProxyUrl() string { if x != nil { return x.ProxyUrl } return "" } func (x *Ft_Proxy) GetProxyHost() string { if x != nil { return x.ProxyHost } return "" } var File_pkg_file_transfer_ft_proto protoreflect.FileDescriptor var file_pkg_file_transfer_ft_proto_rawDesc = []byte{ 0x0a, 0x1a, 0x70, 0x6b, 0x67, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2f, 0x66, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x13, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xcb, 0x04, 0x0a, 0x02, 0x46, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x44, 0x0a, 0x10, 0x64, 0x6f, 0x77, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x64, 0x6f, 0x77, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x40, 0x0a, 0x0e, 0x75, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x75, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x72, 0x65, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x72, 0x65, 0x74, 0x72, 0x79, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x12, 0x40, 0x0a, 0x0e, 0x72, 0x65, 0x74, 0x72, 0x79, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x72, 0x65, 0x74, 0x72, 0x79, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x53, 0x0a, 0x11, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x27, 0x2e, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2e, 0x46, 0x74, 0x2e, 0x4c, 0x6f, 0x61, 0x64, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x0f, 0x6c, 0x6f, 0x61, 0x64, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x37, 0x0a, 0x07, 0x70, 0x72, 0x6f, 0x78, 0x69, 0x65, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2e, 0x46, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x52, 0x07, 0x70, 0x72, 0x6f, 0x78, 0x69, 0x65, 0x73, 0x1a, 0x64, 0x0a, 0x05, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x48, 0x6f, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x55, 0x72, 0x6c, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x48, 0x6f, 0x73, 0x74, 0x22, 0x4c, 0x0a, 0x0f, 0x4c, 0x6f, 0x61, 0x64, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x1b, 0x0a, 0x17, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x5f, 0x66, 0x69, 0x72, 0x73, 0x74, 0x10, 0x00, 0x12, 0x1c, 0x0a, 0x18, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x5f, 0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x10, 0x01, 0x42, 0x34, 0x5a, 0x32, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x3b, 0x66, 0x69, 0x6c, 0x65, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_pkg_file_transfer_ft_proto_rawDescOnce sync.Once file_pkg_file_transfer_ft_proto_rawDescData = file_pkg_file_transfer_ft_proto_rawDesc ) func file_pkg_file_transfer_ft_proto_rawDescGZIP() []byte { file_pkg_file_transfer_ft_proto_rawDescOnce.Do(func() { file_pkg_file_transfer_ft_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_file_transfer_ft_proto_rawDescData) }) return file_pkg_file_transfer_ft_proto_rawDescData } var file_pkg_file_transfer_ft_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_pkg_file_transfer_ft_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_pkg_file_transfer_ft_proto_goTypes = []interface{}{ (Ft_LoadBalanceMode)(0), // 0: go.pkg.filetransfer.Ft.LoadBalanceMode (*Ft)(nil), // 1: go.pkg.filetransfer.Ft (*Ft_Proxy)(nil), // 2: go.pkg.filetransfer.Ft.Proxy (*duration.Duration)(nil), // 3: google.protobuf.Duration } var file_pkg_file_transfer_ft_proto_depIdxs = []int32{ 3, // 0: go.pkg.filetransfer.Ft.download_timeout:type_name -> google.protobuf.Duration 3, // 1: go.pkg.filetransfer.Ft.upload_timeout:type_name -> google.protobuf.Duration 3, // 2: go.pkg.filetransfer.Ft.retry_interval:type_name -> google.protobuf.Duration 0, // 3: go.pkg.filetransfer.Ft.load_balance_mode:type_name -> go.pkg.filetransfer.Ft.LoadBalanceMode 2, // 4: go.pkg.filetransfer.Ft.proxies:type_name -> go.pkg.filetransfer.Ft.Proxy 5, // [5:5] is the sub-list for method output_type 5, // [5:5] is the sub-list for method input_type 5, // [5:5] is the sub-list for extension type_name 5, // [5:5] is the sub-list for extension extendee 0, // [0:5] is the sub-list for field type_name } func init() { file_pkg_file_transfer_ft_proto_init() } func file_pkg_file_transfer_ft_proto_init() { if File_pkg_file_transfer_ft_proto != nil { return } if !protoimpl.UnsafeEnabled { file_pkg_file_transfer_ft_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Ft); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_pkg_file_transfer_ft_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Ft_Proxy); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_pkg_file_transfer_ft_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_pkg_file_transfer_ft_proto_goTypes, DependencyIndexes: file_pkg_file_transfer_ft_proto_depIdxs, EnumInfos: file_pkg_file_transfer_ft_proto_enumTypes, MessageInfos: file_pkg_file_transfer_ft_proto_msgTypes, }.Build() File_pkg_file_transfer_ft_proto = out.File file_pkg_file_transfer_ft_proto_rawDesc = nil file_pkg_file_transfer_ft_proto_goTypes = nil file_pkg_file_transfer_ft_proto_depIdxs = nil } ================================================ FILE: pkg/file-transfer/ft.proto ================================================ syntax = "proto3"; package go.pkg.filetransfer; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/go.pkg.filetransfer;filetransfer"; message Ft { bool enabled = 1; google.protobuf.Duration download_timeout = 2; google.protobuf.Duration upload_timeout = 3; uint32 retry_times = 4; google.protobuf.Duration retry_interval = 5; // 当有多个代理地址时,代理模式, use proxy mode LoadBalanceMode load_balance_mode = 10; enum LoadBalanceMode { load_balance_mode_first = 0; load_balance_mode_random = 1; } repeated Proxy proxies = 11; message Proxy { // target_host即将url中的域名地址改为target_host进行转发, // proxy_url 第三方代理代理进行下载, 如socks5://127.0.0.1:8080 // proxy_host 为proxy_url中的host地址,如果设置了,将代替url中的host // target_addr和target_url都设置值的情况下,优先使用target_addr // reset dns to target_addr in url, string target_host = 1; // reset url to target url string proxy_url = 2; string proxy_host = 3; } } ================================================ FILE: pkg/file-transfer/ft.yaml ================================================ filetransfer: enabled: true download_timeout : 5s upload_timeout : 0s retry_times: 0 # must >= 0 retry_interval: 1s load_balance_mode: load_balance_mode_first proxies: - proxy_url: "" #"http://127.0.0.1:80" proxy_host: "" #"127.0.0.1:8080" target_host: "" #"9.40.34.33:80" ================================================ FILE: pkg/file-transfer/go.mod ================================================ module github.com/kaydxh/golang/pkg/file-transfer go 1.24.0 replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf require ( github.com/golang/protobuf v1.5.4 github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/kaydxh/golang/pkg/logs v0.0.0-20251125132602-62c26b682228 github.com/kaydxh/golang/pkg/viper v0.0.0-00010101000000-000000000000 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.21.0 go.opentelemetry.io/otel v1.38.0 google.golang.org/protobuf v1.36.10 ) require ( github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.28.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/pkg/file-cleanup v0.0.0-20251125132602-62c26b682228 // indirect github.com/kaydxh/golang/pkg/file-rotate v0.0.0-20251125132602-62c26b682228 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/otel/metric v1.38.0 // indirect go.opentelemetry.io/otel/trace v1.38.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect ) ================================================ FILE: pkg/file-transfer/go.sum ================================================ github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kaydxh/golang/pkg/file-cleanup v0.0.0-20251125132602-62c26b682228 h1:Q0arlJiD7BygvPMDHcvTdg1urHqADnd7P2qk3r2HlyE= github.com/kaydxh/golang/pkg/file-cleanup v0.0.0-20251125132602-62c26b682228/go.mod h1:ML4gUddcaOo55zQ9/m8SxjZYYVTJACriuUFcqs1BEd4= github.com/kaydxh/golang/pkg/file-rotate v0.0.0-20251125132602-62c26b682228 h1:7zmih7dDhXTVDxbWy4Cp0OrSqMdQaQzlRUtCzZXMVgc= github.com/kaydxh/golang/pkg/file-rotate v0.0.0-20251125132602-62c26b682228/go.mod h1:DeGVCOtdDQNg6/hVvPwYqeH0EbGcbFiQcKNvMrD+NyY= github.com/kaydxh/golang/pkg/logs v0.0.0-20251125132602-62c26b682228 h1:Z9rIRFQ5Fpa5VibJaRbZeKvcbAET/Ckfwq1nvboE4SE= github.com/kaydxh/golang/pkg/logs v0.0.0-20251125132602-62c26b682228/go.mod h1:QFp3TpQ/DR3CEQpIhmPGWugfDvmvAxK6AvPxMXgHNj0= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= ================================================ FILE: pkg/file-transfer/upload/upload.svr.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 upload import ( "fmt" "io" "os" "path/filepath" "strings" md5_ "github.com/kaydxh/golang/go/crypto/md5" io_ "github.com/kaydxh/golang/go/io" "github.com/kaydxh/golang/go/sync/atomic" atomic_ "github.com/kaydxh/golang/go/sync/atomic" ) type UploadPartInput struct { PartId uint32 Offset int64 Length int64 Md5Sum string } const tmpFileSuffix = "_.tmp" func UploadFile( r io.Reader, filePath string, md5Sum string, ) error { if filePath == "" { return fmt.Errorf("invalid filePath") } //check path absFilePath, err := filepath.Abs(filePath) if strings.Contains(absFilePath, "..") { err = fmt.Errorf("invalid filePath: %v", absFilePath) return err } var mu atomic_.FileLock = atomic.FileLock(filepath.Join("./", absFilePath)) err = mu.TryLock() if err != nil { return err } unlockFun := func() error { err = mu.TryUnLock() if err != nil { return err } return nil } defer unlockFun() if md5Sum != "" { sum, err := md5_.SumReader(r) if err != nil { return err } gotSum := strings.ToLower(sum) expectSum := strings.ToLower(md5Sum) if gotSum != expectSum { return fmt.Errorf( "failed to check md5Sum, got: %v, expect: %v", gotSum, expectSum, ) } } err = io_.WriteReader(filePath, r) if err != nil { return err } return nil } func UploadMultipart( r io.Reader, partInput *UploadPartInput, filePath string, ) error { if partInput == nil { return fmt.Errorf("invalid partInput") } if filePath == "" { return fmt.Errorf("invalid filePath") } //check path absFilePath, err := filepath.Abs(filePath) if strings.Contains(absFilePath, "..") { err = fmt.Errorf("invalid filePath: %v", absFilePath) return err } var mu atomic_.FileLock = atomic.FileLock(filepath.Join("./", absFilePath)) err = mu.TryLock() if err != nil { return err } unlockFun := func() error { err = mu.TryUnLock() if err != nil { return err } return nil } defer unlockFun() if partInput.Md5Sum != "" { sum, err := md5_.SumReader(r) if err != nil { return err } gotSum := strings.ToLower(sum) expectSum := strings.ToLower(partInput.Md5Sum) if gotSum != expectSum { return fmt.Errorf( "failed to check md5Sum, got: %v, expect: %v", gotSum, expectSum, ) } } tmpFilePath := filePath + tmpFileSuffix err = io_.WriteReaderAt( tmpFilePath, r, partInput.Offset, partInput.Length, ) if err != nil { return err } return nil } func CompleteMultipartUpload( filePath string, md5Sum string) error { if filePath == "" { return fmt.Errorf("invalid filePath") } tmpFilePath := filePath + tmpFileSuffix if md5Sum != "" { sum, err := md5_.SumFile(tmpFilePath) if err != nil { return err } gotSum := strings.ToLower(sum) expectSum := strings.ToLower(md5Sum) if gotSum != expectSum { return fmt.Errorf( "failed to check md5Sum, got: %v, expect: %v", gotSum, expectSum, ) } } _, err := os.Stat(tmpFilePath) if err != nil { return fmt.Errorf("file: %v is not existed", tmpFilePath) } err = os.Rename(tmpFilePath, filePath) if err != nil { return fmt.Errorf("failed to Rename: %v to %v", tmpFilePath, filePath) } return nil } ================================================ FILE: pkg/file-transfer/upload/upload.svr_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 upload_test import ( "mime/multipart" "path/filepath" "testing" os_ "github.com/kaydxh/golang/go/os" upload_ "github.com/kaydxh/golang/pkg/file-transfer/upload" ) func TestUploadMultipart(t *testing.T) { var file multipart.FileHeader srcFile, err := file.Open() if err != nil { return } defer srcFile.Close() workDir, _ := os_.Getwd() testFilePath := filepath.Join(workDir, "test-file-upload") partInput := &upload_.UploadPartInput{ PartId: 1, Offset: 0, Length: 18, } err = upload_.UploadMultipart(srcFile, partInput, testFilePath) if err != nil { t.Errorf("expect nil, got %v", err) return } } func TestCompleteMultipartUpload(t *testing.T) { workDir, _ := os_.Getwd() testFilePath := filepath.Join(workDir, "test-file-upload") err := upload_.CompleteMultipartUpload( testFilePath, "", ) if err != nil { t.Errorf("expect nil, got %v", err) return } } ================================================ FILE: pkg/fsnotify/config.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 fsnotify import ( "context" viper_ "github.com/kaydxh/golang/pkg/viper" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) type Config struct { Proto Fsnotify opts struct { // If set, overrides params below viper *viper.Viper } } type completedConfig struct { *Config completeError error } type CompletedConfig struct { // Embed a private pointer that cannot be instantiated outside of this package. *completedConfig } func (c *completedConfig) New(ctx context.Context) (*FsnotifyService, error) { logrus.Infof("Installing Fsnotify") if c.completeError != nil { return nil, c.completeError } if !c.Proto.GetEnabled() { return nil, nil } rs, err := c.install(ctx) if err != nil { return nil, err } logrus.Infof("Installed Fsnotify") return rs, nil } func (c *completedConfig) install(ctx context.Context) (*FsnotifyService, error) { fn, err := NewFsnotifyService(c.Proto.GetFilePaths()) if err != nil { return nil, err } fn.Run(ctx) return fn, nil } // Complete set default ServerRunOptions. func (c *Config) Complete() CompletedConfig { err := c.loadViper() if err != nil { return CompletedConfig{&completedConfig{ Config: c, completeError: err, }} } return CompletedConfig{&completedConfig{Config: c}} } func (c *Config) loadViper() error { if c.opts.viper != nil { return viper_.UnmarshalProtoMessageWithJsonPb(c.opts.viper, &c.Proto) } return nil } func NewConfig(options ...ConfigOption) *Config { c := &Config{} c.ApplyOptions(options...) return c } ================================================ FILE: pkg/fsnotify/config.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 fsnotify import ( "github.com/spf13/viper" ) func WithViper(v *viper.Viper) ConfigOption { return ConfigOptionFunc(func(c *Config) { c.opts.viper = v }) } ================================================ FILE: pkg/fsnotify/config_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 fsnotify // A ConfigOption sets options. type ConfigOption interface { apply(*Config) } // EmptyConfigOption does not alter the configuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyConfigOption struct{} func (EmptyConfigOption) apply(*Config) {} // ConfigOptionFunc wraps a function that modifies Client into an // implementation of the ConfigOption interface. type ConfigOptionFunc func(*Config) func (f ConfigOptionFunc) apply(do *Config) { f(do) } // sample code for option, default for nothing to change func _ConfigOptionWithDefault() ConfigOption { return ConfigOptionFunc(func(*Config) { // nothing to change }) } func (o *Config) ApplyOptions(options ...ConfigOption) *Config { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/fsnotify/fsnotify.go ================================================ package fsnotify import ( "context" "fmt" "os" "path/filepath" "sync" "sync/atomic" "github.com/fsnotify/fsnotify" "github.com/kaydxh/golang/go/errors" os_ "github.com/kaydxh/golang/go/os" "github.com/sirupsen/logrus" ) type EventCallbackFunc func(ctx context.Context, path string) type FsnotifyOptions struct { CreateCallbackFunc EventCallbackFunc WriteCallbackFunc EventCallbackFunc RemoveCallbackFunc EventCallbackFunc } type FsnotifyService struct { watcher *fsnotify.Watcher paths []string opts FsnotifyOptions inShutdown atomic.Bool mu sync.Mutex cancel func() } // paths can also be dir or file or both of them func NewFsnotifyService(paths []string, opts ...FsnotifyOption) (*FsnotifyService, error) { watcher, err := fsnotify.NewWatcher() if err != nil { return nil, err } if len(paths) == 0 { return nil, fmt.Errorf("paths is empty") } for _, path := range paths { ok, err := os_.PathExist(path) if err != nil { return nil, err } if !ok { return nil, fmt.Errorf("%s is not exist", path) } } fs := &FsnotifyService{ watcher: watcher, paths: paths, } fs.ApplyOptions(opts...) return fs, nil } func (srv *FsnotifyService) logger() logrus.FieldLogger { return logrus.WithField("module", "FsnotifyService") } func (srv *FsnotifyService) Run(ctx context.Context) error { logger := srv.logger() logger.Infoln("FsnotifyService Run") if srv.inShutdown.Load() { logger.Infoln("FsnotifyService Shutdown") return fmt.Errorf("server closed") } go func() { errors.HandleError(srv.Serve(ctx)) }() return nil } func (srv *FsnotifyService) Serve(ctx context.Context) error { logger := srv.logger() logger.Infoln("FsnotifyService Serve") if srv.inShutdown.Load() { err := fmt.Errorf("server closed") logger.WithError(err).Errorf("FsnotifyService Serve canceled") return err } defer srv.inShutdown.Store(true) ctx, cancel := context.WithCancel(ctx) srv.mu.Lock() srv.cancel = cancel srv.mu.Unlock() defer func() { err := srv.watcher.Close() if err != nil { logger.WithError(err).Errorf("failed to close FsnotifyService watcher") } }() err := srv.AddWatchPaths(false, srv.paths...) if err != nil { logger.WithError(err).Errorf("failed to add watcher for path: %v", srv.paths) return err } for { select { case ev, ok := <-srv.watcher.Events: if !ok { continue } if ev.Op&fsnotify.Create != 0 { logger.Infof("%s happen create event", ev.Name) srv.AddWatchPaths(false, ev.Name) if srv.opts.CreateCallbackFunc != nil { srv.opts.CreateCallbackFunc(ctx, ev.Name) } } if ev.Op&fsnotify.Write != 0 { logger.Infof("%s happen write event", ev.Name) srv.AddWatchPaths(false, ev.Name) if srv.opts.WriteCallbackFunc != nil { srv.opts.WriteCallbackFunc(ctx, ev.Name) } } if ev.Op&fsnotify.Remove != 0 { logger.Infof("%s happen remove event", ev.Name) srv.AddWatchPaths(true, ev.Name) if srv.opts.RemoveCallbackFunc != nil { srv.opts.RemoveCallbackFunc(ctx, ev.Name) } } if ev.Op&fsnotify.Rename != 0 { logger.Infof("%s happen rename event", ev.Name) } if ev.Op&fsnotify.Chmod != 0 { logger.Infof("%s happen chmod event", ev.Name) } case <-ctx.Done(): logger.WithError(ctx.Err()).Errorf("server canceld") return ctx.Err() } } } // Add starts watching the named directory (support recursively). func (srv *FsnotifyService) AddWatchPath(unWatch bool, path string) error { logger := srv.logger() ok, err := os_.IsDir(path) if err != nil { return err } if ok { return filepath.Walk(path, func(walkPath string, fi os.FileInfo, err error) error { if err != nil { logger.WithError(err).Errorf("failed to walk dir: %v", walkPath) return err } if fi.IsDir() { return srv.Add(unWatch, walkPath) } return nil }) } else { return srv.Add(unWatch, path) } } // Add starts watching the named directory (non-recursively). func (srv *FsnotifyService) Add(unWatch bool, path string) (err error) { logger := srv.logger() if unWatch { err = srv.watcher.Remove(path) } else { err = srv.watcher.Add(path) } if err != nil { logger.WithError(err).Errorf("failed to add watcher for path: %v, ", path) return err } logger.Infof("add watcher for path: %v", path) return nil } func (srv *FsnotifyService) AddWatchPaths(unWatch bool, paths ...string) error { for _, path := range paths { err := srv.AddWatchPath(unWatch, path) if err != nil { return err } } return nil } func (srv *FsnotifyService) Shutdown() { srv.inShutdown.Store(true) srv.mu.Lock() defer srv.mu.Unlock() if srv.cancel != nil { srv.cancel() } } ================================================ FILE: pkg/fsnotify/fsnotify.option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 fsnotify func WithCreateCallbackFunc(fn EventCallbackFunc) FsnotifyOption { return FsnotifyOptionFunc(func(r *FsnotifyService) { r.opts.CreateCallbackFunc = fn }) } func WithWriteCallbackFunc(fn EventCallbackFunc) FsnotifyOption { return FsnotifyOptionFunc(func(r *FsnotifyService) { r.opts.WriteCallbackFunc = fn }) } func WithRemoveCallbackFunc(fn EventCallbackFunc) FsnotifyOption { return FsnotifyOptionFunc(func(r *FsnotifyService) { r.opts.RemoveCallbackFunc = fn }) } ================================================ FILE: pkg/fsnotify/fsnotify.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.13.0 // source: pkg/fsnotify/fsnotify.proto package fsnotify import ( _ "github.com/golang/protobuf/ptypes/duration" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Fsnotify struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` FilePaths []string `protobuf:"bytes,2,rep,name=file_paths,json=filePaths,proto3" json:"file_paths,omitempty"` } func (x *Fsnotify) Reset() { *x = Fsnotify{} if protoimpl.UnsafeEnabled { mi := &file_pkg_fsnotify_fsnotify_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Fsnotify) String() string { return protoimpl.X.MessageStringOf(x) } func (*Fsnotify) ProtoMessage() {} func (x *Fsnotify) ProtoReflect() protoreflect.Message { mi := &file_pkg_fsnotify_fsnotify_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Fsnotify.ProtoReflect.Descriptor instead. func (*Fsnotify) Descriptor() ([]byte, []int) { return file_pkg_fsnotify_fsnotify_proto_rawDescGZIP(), []int{0} } func (x *Fsnotify) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *Fsnotify) GetFilePaths() []string { if x != nil { return x.FilePaths } return nil } var File_pkg_fsnotify_fsnotify_proto protoreflect.FileDescriptor var file_pkg_fsnotify_fsnotify_proto_rawDesc = []byte{ 0x0a, 0x1b, 0x70, 0x6b, 0x67, 0x2f, 0x66, 0x73, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x2f, 0x66, 0x73, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0f, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x66, 0x73, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x43, 0x0a, 0x08, 0x46, 0x73, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x66, 0x69, 0x6c, 0x65, 0x50, 0x61, 0x74, 0x68, 0x73, 0x42, 0x2c, 0x5a, 0x2a, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x2e, 0x70, 0x6b, 0x67, 0x2e, 0x66, 0x73, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x3b, 0x66, 0x73, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_pkg_fsnotify_fsnotify_proto_rawDescOnce sync.Once file_pkg_fsnotify_fsnotify_proto_rawDescData = file_pkg_fsnotify_fsnotify_proto_rawDesc ) func file_pkg_fsnotify_fsnotify_proto_rawDescGZIP() []byte { file_pkg_fsnotify_fsnotify_proto_rawDescOnce.Do(func() { file_pkg_fsnotify_fsnotify_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_fsnotify_fsnotify_proto_rawDescData) }) return file_pkg_fsnotify_fsnotify_proto_rawDescData } var file_pkg_fsnotify_fsnotify_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_pkg_fsnotify_fsnotify_proto_goTypes = []interface{}{ (*Fsnotify)(nil), // 0: go.pkg.fsnotify.Fsnotify } var file_pkg_fsnotify_fsnotify_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_pkg_fsnotify_fsnotify_proto_init() } func file_pkg_fsnotify_fsnotify_proto_init() { if File_pkg_fsnotify_fsnotify_proto != nil { return } if !protoimpl.UnsafeEnabled { file_pkg_fsnotify_fsnotify_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Fsnotify); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_pkg_fsnotify_fsnotify_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_pkg_fsnotify_fsnotify_proto_goTypes, DependencyIndexes: file_pkg_fsnotify_fsnotify_proto_depIdxs, MessageInfos: file_pkg_fsnotify_fsnotify_proto_msgTypes, }.Build() File_pkg_fsnotify_fsnotify_proto = out.File file_pkg_fsnotify_fsnotify_proto_rawDesc = nil file_pkg_fsnotify_fsnotify_proto_goTypes = nil file_pkg_fsnotify_fsnotify_proto_depIdxs = nil } ================================================ FILE: pkg/fsnotify/fsnotify.proto ================================================ syntax = "proto3"; package go.pkg.fsnotify; import "google/protobuf/duration.proto"; option go_package = "github.com/kaydxh/go.pkg.fsnotify;fsnotify"; message Fsnotify { bool enabled = 1; repeated string file_paths = 2; } ================================================ FILE: pkg/fsnotify/fsnotify.yaml ================================================ fsnotify: enabled: true file_paths: [ "./testdata" ] ================================================ FILE: pkg/fsnotify/fsnotify_option.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 fsnotify // A FsnotifyOption sets options. type FsnotifyOption interface { apply(*FsnotifyService) } // EmptyFsnotifyUrlOption does not alter the Fsnotifyuration. It can be embedded // in another structure to build custom options. // // This API is EXPERIMENTAL. type EmptyFsnotifyOption struct{} func (EmptyFsnotifyOption) apply(*FsnotifyService) {} // FsnotifyOptionFunc wraps a function that modifies FsnotifyService into an // implementation of the FsnotifyOption interface. type FsnotifyOptionFunc func(*FsnotifyService) func (f FsnotifyOptionFunc) apply(do *FsnotifyService) { f(do) } // sample code for option, default for nothing to change func _FsnotifyOptionWithDefault() FsnotifyOption { return FsnotifyOptionFunc(func(*FsnotifyService) { // nothing to change }) } func (o *FsnotifyService) ApplyOptions(options ...FsnotifyOption) *FsnotifyService { for _, opt := range options { if opt == nil { continue } opt.apply(o) } return o } ================================================ FILE: pkg/fsnotify/fsnotify_test.go ================================================ package fsnotify_test import ( "context" "testing" fsnotify_ "github.com/kaydxh/golang/pkg/fsnotify" viper_ "github.com/kaydxh/golang/pkg/viper" ) func TestFsnotify(t *testing.T) { cfgFile := "./fsnotify.yaml" config := fsnotify_.NewConfig(fsnotify_.WithViper(viper_.GetViper(cfgFile, "fsnotify"))) fn, err := config.Complete().New(context.Background()) if err != nil { t.Fatalf("failed to new config err: %v", err) } fn.ApplyOptions(fsnotify_.WithWriteCallbackFunc(func(ctx context.Context, path string) { t.Logf("%s write call back", path) })) select {} } ================================================ FILE: pkg/fsnotify/go.mod ================================================ module github.com/kaydxh/golang/pkg/fsnotify go 1.24.0 replace github.com/kaydxh/golang/go => ../../go replace github.com/kaydxh/golang/pkg/viper => ../viper replace github.com/kaydxh/golang/pkg/protobuf => ../protobuf require ( github.com/fsnotify/fsnotify v1.9.0 github.com/golang/protobuf v1.5.4 github.com/kaydxh/golang/go v0.0.0-20251125160242-e06b25c89946 github.com/kaydxh/golang/pkg/viper v0.0.0-00010101000000-000000000000 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.21.0 google.golang.org/protobuf v1.36.10 ) require ( github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/gabriel-vasile/mimetype v1.4.10 // indirect github.com/gin-gonic/gin v1.11.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.28.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaydxh/golang/pkg/protobuf v0.0.0-00010101000000-000000000000 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.46.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/grpc v1.77.0 // indirect ) ================================================ FILE: pkg/fsnotify/go.sum ================================================ github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: pkg/gocv/cgo/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.10) project(sdk-go VERSION 1.0 DESCRIPTION "CGO Library" LANGUAGES CXX C) if(NOT CMAKE_BUILD_TYPE) set (CMAKE_BUILD_TYPE "Debug") endif() set(CXX_FLAGS -g -DCHECK_PTHREAD_RETURN_VALUE -D_FILE_OFFSET_BITS=64 -Wall -Wextra -Werror # -Wconversion -Wno-unused-parameter # -Wold-style-cast -Woverloaded-virtual -Wpointer-arith -Wshadow -Wwrite-strings -march=native -std=c++11 -rdynamic ) set(CMAKE_CXX_STANDARD 11) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/") add_subdirectory(api/openapi-spec) ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/CMakeLists.txt ================================================ add_custom_target(openapi-spec) find_package(Protobuf) if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty.srv.cmake) include(${CMAKE_CURRENT_SOURCE_DIR}/thirdparty.srv.cmake) endif () GET_MODEL_DIRS(${CMAKE_CURRENT_SOURCE_DIR} _module_dirs) FOREACH (_module_dir ${_module_dirs}) if (EXISTS ${_module_dir}) file(RELATIVE_PATH _rel_module_dir ${CMAKE_CURRENT_SOURCE_DIR} ${_module_dir}) message(STATUS "add_subdirectory=${_rel_module_dir}") add_subdirectory(${_rel_module_dir}) # add_dependencies(openapi-spec proto-${_rel_module_dir}) endif() ENDFOREACH () ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/Makefile ================================================ MAKEFILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) TARGET := $(shell basename ${MAKEFILE_DIR}) PROJECT_ROOT_PATH := ${MAKEFILE_DIR}/../../ $(info ${PROJECT_ROOT_PATH}) .PHONY: generate generate: @echo " > starting generate protocol buffers for target ${TARGET} in golang" @bash -c "go generate ../api/openapi-spec/proto.gen.go" @echo " > compiling protocol buffers by cpp" @if [[ -f "${PROJECT_ROOT_PATH}/build" ]]; then rm -Rv "${PROJECT_ROOT_PATH}/build"; fi @mkdir -p ${PROJECT_ROOT_PATH}/build; cd ${PROJECT_ROOT_PATH}/build; cmake .. @cmake --build ${PROJECT_ROOT_PATH}/build --target ${TARGET} -- -j `nproc`; @echo " > install generated protocol buffers by cpp" @cd ${PROJECT_ROOT_PATH}/build; cmake --install . ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/gocv/CMakeLists.txt ================================================ find_package(Protobuf) list(APPEND IMPORT_DIRS "${PROJECT_SOURCE_DIR}") GENERATE_PROTOBUF_LIB("${IMPORT_DIRS}" "proto-types") ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/gocv/gocv.magick.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.17.3 // source: gocv/gocv.magick.proto package gocv import ( code "github.com/kaydxh/golang/pkg/gocv/cgo/api/openapi-spec/types/code" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type OrientationType int32 const ( OrientationType_UndefinedOrientation OrientationType = 0 OrientationType_TopLeftOrientation OrientationType = 1 OrientationType_TopRightOrientation OrientationType = 2 OrientationType_BottomRightOrientation OrientationType = 3 OrientationType_BottomLeftOrientation OrientationType = 4 OrientationType_LeftTopOrientation OrientationType = 5 OrientationType_RightTopOrientation OrientationType = 6 OrientationType_RightBottomOrientation OrientationType = 7 OrientationType_LeftBottomOrientation OrientationType = 8 ) // Enum value maps for OrientationType. var ( OrientationType_name = map[int32]string{ 0: "UndefinedOrientation", 1: "TopLeftOrientation", 2: "TopRightOrientation", 3: "BottomRightOrientation", 4: "BottomLeftOrientation", 5: "LeftTopOrientation", 6: "RightTopOrientation", 7: "RightBottomOrientation", 8: "LeftBottomOrientation", } OrientationType_value = map[string]int32{ "UndefinedOrientation": 0, "TopLeftOrientation": 1, "TopRightOrientation": 2, "BottomRightOrientation": 3, "BottomLeftOrientation": 4, "LeftTopOrientation": 5, "RightTopOrientation": 6, "RightBottomOrientation": 7, "LeftBottomOrientation": 8, } ) func (x OrientationType) Enum() *OrientationType { p := new(OrientationType) *p = x return p } func (x OrientationType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (OrientationType) Descriptor() protoreflect.EnumDescriptor { return file_gocv_gocv_magick_proto_enumTypes[0].Descriptor() } func (OrientationType) Type() protoreflect.EnumType { return &file_gocv_gocv_magick_proto_enumTypes[0] } func (x OrientationType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use OrientationType.Descriptor instead. func (OrientationType) EnumDescriptor() ([]byte, []int) { return file_gocv_gocv_magick_proto_rawDescGZIP(), []int{0} } // graphics-magick/include/magick/colorspace.h type ColorspaceType int32 const ( ColorspaceType_UndefinedColorspace ColorspaceType = 0 ColorspaceType_RGBColorspace ColorspaceType = 1 // Plain old RGB colorspace ColorspaceType_GRAYColorspace ColorspaceType = 2 // Plain old full-range grayscale ColorspaceType_TransparentColorspace ColorspaceType = 3 // RGB but preserve matte channel during quantize ColorspaceType_OHTAColorspace ColorspaceType = 4 ColorspaceType_XYZColorspace ColorspaceType = 5 // CIE XYZ ColorspaceType_YCCColorspace ColorspaceType = 6 // Kodak PhotoCD PhotoYCC ColorspaceType_YIQColorspace ColorspaceType = 7 ColorspaceType_YPbPrColorspace ColorspaceType = 8 ColorspaceType_YUVColorspace ColorspaceType = 9 ColorspaceType_CMYKColorspace ColorspaceType = 10 // Cyan, magenta, yellow, black, alpha ColorspaceType_sRGBColorspace ColorspaceType = 11 // Kodak PhotoCD sRGB ColorspaceType_HSLColorspace ColorspaceType = 12 // Hue, saturation, luminosity ColorspaceType_HWBColorspace ColorspaceType = 13 // Hue, whiteness, blackness ColorspaceType_LABColorspace ColorspaceType = 14 // LAB colorspace not supported yet other than via lcms ColorspaceType_CineonLogRGBColorspace ColorspaceType = 15 // RGB data with Cineon Log scaling, 2.048 density range ColorspaceType_Rec601LumaColorspace ColorspaceType = 16 // Luma (Y) according to ITU-R 601 ColorspaceType_Rec601YCbCrColorspace ColorspaceType = 17 // YCbCr according to ITU-R 601 ColorspaceType_Rec709LumaColorspace ColorspaceType = 18 // Luma (Y) according to ITU-R 709 ColorspaceType_Rec709YCbCrColorspace ColorspaceType = 19 // YCbCr according to ITU-R 709 ) // Enum value maps for ColorspaceType. var ( ColorspaceType_name = map[int32]string{ 0: "UndefinedColorspace", 1: "RGBColorspace", 2: "GRAYColorspace", 3: "TransparentColorspace", 4: "OHTAColorspace", 5: "XYZColorspace", 6: "YCCColorspace", 7: "YIQColorspace", 8: "YPbPrColorspace", 9: "YUVColorspace", 10: "CMYKColorspace", 11: "sRGBColorspace", 12: "HSLColorspace", 13: "HWBColorspace", 14: "LABColorspace", 15: "CineonLogRGBColorspace", 16: "Rec601LumaColorspace", 17: "Rec601YCbCrColorspace", 18: "Rec709LumaColorspace", 19: "Rec709YCbCrColorspace", } ColorspaceType_value = map[string]int32{ "UndefinedColorspace": 0, "RGBColorspace": 1, "GRAYColorspace": 2, "TransparentColorspace": 3, "OHTAColorspace": 4, "XYZColorspace": 5, "YCCColorspace": 6, "YIQColorspace": 7, "YPbPrColorspace": 8, "YUVColorspace": 9, "CMYKColorspace": 10, "sRGBColorspace": 11, "HSLColorspace": 12, "HWBColorspace": 13, "LABColorspace": 14, "CineonLogRGBColorspace": 15, "Rec601LumaColorspace": 16, "Rec601YCbCrColorspace": 17, "Rec709LumaColorspace": 18, "Rec709YCbCrColorspace": 19, } ) func (x ColorspaceType) Enum() *ColorspaceType { p := new(ColorspaceType) *p = x return p } func (x ColorspaceType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ColorspaceType) Descriptor() protoreflect.EnumDescriptor { return file_gocv_gocv_magick_proto_enumTypes[1].Descriptor() } func (ColorspaceType) Type() protoreflect.EnumType { return &file_gocv_gocv_magick_proto_enumTypes[1] } func (x ColorspaceType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ColorspaceType.Descriptor instead. func (ColorspaceType) EnumDescriptor() ([]byte, []int) { return file_gocv_gocv_magick_proto_rawDescGZIP(), []int{1} } type MagickInitializeMagickRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"` } func (x *MagickInitializeMagickRequest) Reset() { *x = MagickInitializeMagickRequest{} if protoimpl.UnsafeEnabled { mi := &file_gocv_gocv_magick_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MagickInitializeMagickRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*MagickInitializeMagickRequest) ProtoMessage() {} func (x *MagickInitializeMagickRequest) ProtoReflect() protoreflect.Message { mi := &file_gocv_gocv_magick_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MagickInitializeMagickRequest.ProtoReflect.Descriptor instead. func (*MagickInitializeMagickRequest) Descriptor() ([]byte, []int) { return file_gocv_gocv_magick_proto_rawDescGZIP(), []int{0} } func (x *MagickInitializeMagickRequest) GetPath() string { if x != nil { return x.Path } return "" } type MagickInitializeMagickResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Error *code.CgoError `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` } func (x *MagickInitializeMagickResponse) Reset() { *x = MagickInitializeMagickResponse{} if protoimpl.UnsafeEnabled { mi := &file_gocv_gocv_magick_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MagickInitializeMagickResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*MagickInitializeMagickResponse) ProtoMessage() {} func (x *MagickInitializeMagickResponse) ProtoReflect() protoreflect.Message { mi := &file_gocv_gocv_magick_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MagickInitializeMagickResponse.ProtoReflect.Descriptor instead. func (*MagickInitializeMagickResponse) Descriptor() ([]byte, []int) { return file_gocv_gocv_magick_proto_rawDescGZIP(), []int{1} } func (x *MagickInitializeMagickResponse) GetError() *code.CgoError { if x != nil { return x.Error } return nil } type MagickImageDecodeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Image []byte `protobuf:"bytes,1,opt,name=image,proto3" json:"image,omitempty"` TargetColorSpace string `protobuf:"bytes,2,opt,name=target_color_space,json=targetColorSpace,proto3" json:"target_color_space,omitempty"` // support BGR BGRA GRA GRAYA, default BGRA } func (x *MagickImageDecodeRequest) Reset() { *x = MagickImageDecodeRequest{} if protoimpl.UnsafeEnabled { mi := &file_gocv_gocv_magick_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MagickImageDecodeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*MagickImageDecodeRequest) ProtoMessage() {} func (x *MagickImageDecodeRequest) ProtoReflect() protoreflect.Message { mi := &file_gocv_gocv_magick_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MagickImageDecodeRequest.ProtoReflect.Descriptor instead. func (*MagickImageDecodeRequest) Descriptor() ([]byte, []int) { return file_gocv_gocv_magick_proto_rawDescGZIP(), []int{2} } func (x *MagickImageDecodeRequest) GetImage() []byte { if x != nil { return x.Image } return nil } func (x *MagickImageDecodeRequest) GetTargetColorSpace() string { if x != nil { return x.TargetColorSpace } return "" } type MagickImageDecodeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Error *code.CgoError `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` CvMatPointer int64 `protobuf:"varint,2,opt,name=cv_mat_pointer,json=cvMatPointer,proto3" json:"cv_mat_pointer,omitempty"` // pointer of cv::Mat Rows int64 `protobuf:"varint,3,opt,name=rows,proto3" json:"rows,omitempty"` // Image height Columns int64 `protobuf:"varint,4,opt,name=columns,proto3" json:"columns,omitempty"` // Image width Magick string `protobuf:"bytes,5,opt,name=magick,proto3" json:"magick,omitempty"` // File type magick identifier (.e.g "GIF") OrientationType OrientationType `protobuf:"varint,6,opt,name=orientation_type,json=orientationType,proto3,enum=sdk.api.gocv.OrientationType" json:"orientation_type,omitempty"` ColorspaceType ColorspaceType `protobuf:"varint,7,opt,name=colorspace_type,json=colorspaceType,proto3,enum=sdk.api.gocv.ColorspaceType" json:"colorspace_type,omitempty"` } func (x *MagickImageDecodeResponse) Reset() { *x = MagickImageDecodeResponse{} if protoimpl.UnsafeEnabled { mi := &file_gocv_gocv_magick_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MagickImageDecodeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*MagickImageDecodeResponse) ProtoMessage() {} func (x *MagickImageDecodeResponse) ProtoReflect() protoreflect.Message { mi := &file_gocv_gocv_magick_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MagickImageDecodeResponse.ProtoReflect.Descriptor instead. func (*MagickImageDecodeResponse) Descriptor() ([]byte, []int) { return file_gocv_gocv_magick_proto_rawDescGZIP(), []int{3} } func (x *MagickImageDecodeResponse) GetError() *code.CgoError { if x != nil { return x.Error } return nil } func (x *MagickImageDecodeResponse) GetCvMatPointer() int64 { if x != nil { return x.CvMatPointer } return 0 } func (x *MagickImageDecodeResponse) GetRows() int64 { if x != nil { return x.Rows } return 0 } func (x *MagickImageDecodeResponse) GetColumns() int64 { if x != nil { return x.Columns } return 0 } func (x *MagickImageDecodeResponse) GetMagick() string { if x != nil { return x.Magick } return "" } func (x *MagickImageDecodeResponse) GetOrientationType() OrientationType { if x != nil { return x.OrientationType } return OrientationType_UndefinedOrientation } func (x *MagickImageDecodeResponse) GetColorspaceType() ColorspaceType { if x != nil { return x.ColorspaceType } return ColorspaceType_UndefinedColorspace } var File_gocv_gocv_magick_proto protoreflect.FileDescriptor var file_gocv_gocv_magick_proto_rawDesc = []byte{ 0x0a, 0x16, 0x67, 0x6f, 0x63, 0x76, 0x2f, 0x67, 0x6f, 0x63, 0x76, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x73, 0x64, 0x6b, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x67, 0x6f, 0x63, 0x76, 0x1a, 0x2d, 0x61, 0x70, 0x69, 0x2f, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2d, 0x73, 0x70, 0x65, 0x63, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x2f, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x33, 0x0a, 0x1d, 0x4d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x4d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x22, 0x50, 0x0a, 0x1e, 0x4d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x4d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2e, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x2e, 0x43, 0x67, 0x6f, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5e, 0x0a, 0x18, 0x4d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x49, 0x6d, 0x61, 0x67, 0x65, 0x44, 0x65, 0x63, 0x6f, 0x64, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x12, 0x2c, 0x0a, 0x12, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x22, 0xc8, 0x02, 0x0a, 0x19, 0x4d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x49, 0x6d, 0x61, 0x67, 0x65, 0x44, 0x65, 0x63, 0x6f, 0x64, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2e, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x2e, 0x43, 0x67, 0x6f, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x24, 0x0a, 0x0e, 0x63, 0x76, 0x5f, 0x6d, 0x61, 0x74, 0x5f, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x63, 0x76, 0x4d, 0x61, 0x74, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x6f, 0x77, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x72, 0x6f, 0x77, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x6d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6d, 0x61, 0x67, 0x69, 0x63, 0x6b, 0x12, 0x48, 0x0a, 0x10, 0x6f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1d, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x67, 0x6f, 0x63, 0x76, 0x2e, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0f, 0x6f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x45, 0x0a, 0x0f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1c, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x67, 0x6f, 0x63, 0x76, 0x2e, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0e, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x54, 0x79, 0x70, 0x65, 0x2a, 0xfb, 0x01, 0x0a, 0x0f, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x18, 0x0a, 0x14, 0x55, 0x6e, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x65, 0x64, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x00, 0x12, 0x16, 0x0a, 0x12, 0x54, 0x6f, 0x70, 0x4c, 0x65, 0x66, 0x74, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x54, 0x6f, 0x70, 0x52, 0x69, 0x67, 0x68, 0x74, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x02, 0x12, 0x1a, 0x0a, 0x16, 0x42, 0x6f, 0x74, 0x74, 0x6f, 0x6d, 0x52, 0x69, 0x67, 0x68, 0x74, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x03, 0x12, 0x19, 0x0a, 0x15, 0x42, 0x6f, 0x74, 0x74, 0x6f, 0x6d, 0x4c, 0x65, 0x66, 0x74, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x04, 0x12, 0x16, 0x0a, 0x12, 0x4c, 0x65, 0x66, 0x74, 0x54, 0x6f, 0x70, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x05, 0x12, 0x17, 0x0a, 0x13, 0x52, 0x69, 0x67, 0x68, 0x74, 0x54, 0x6f, 0x70, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x06, 0x12, 0x1a, 0x0a, 0x16, 0x52, 0x69, 0x67, 0x68, 0x74, 0x42, 0x6f, 0x74, 0x74, 0x6f, 0x6d, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x07, 0x12, 0x19, 0x0a, 0x15, 0x4c, 0x65, 0x66, 0x74, 0x42, 0x6f, 0x74, 0x74, 0x6f, 0x6d, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x08, 0x2a, 0xc7, 0x03, 0x0a, 0x0e, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x17, 0x0a, 0x13, 0x55, 0x6e, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x65, 0x64, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x00, 0x12, 0x11, 0x0a, 0x0d, 0x52, 0x47, 0x42, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x47, 0x52, 0x41, 0x59, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x02, 0x12, 0x19, 0x0a, 0x15, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x03, 0x12, 0x12, 0x0a, 0x0e, 0x4f, 0x48, 0x54, 0x41, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x58, 0x59, 0x5a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x05, 0x12, 0x11, 0x0a, 0x0d, 0x59, 0x43, 0x43, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x06, 0x12, 0x11, 0x0a, 0x0d, 0x59, 0x49, 0x51, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x07, 0x12, 0x13, 0x0a, 0x0f, 0x59, 0x50, 0x62, 0x50, 0x72, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x08, 0x12, 0x11, 0x0a, 0x0d, 0x59, 0x55, 0x56, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x09, 0x12, 0x12, 0x0a, 0x0e, 0x43, 0x4d, 0x59, 0x4b, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x0a, 0x12, 0x12, 0x0a, 0x0e, 0x73, 0x52, 0x47, 0x42, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x0b, 0x12, 0x11, 0x0a, 0x0d, 0x48, 0x53, 0x4c, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x0c, 0x12, 0x11, 0x0a, 0x0d, 0x48, 0x57, 0x42, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x0d, 0x12, 0x11, 0x0a, 0x0d, 0x4c, 0x41, 0x42, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x0e, 0x12, 0x1a, 0x0a, 0x16, 0x43, 0x69, 0x6e, 0x65, 0x6f, 0x6e, 0x4c, 0x6f, 0x67, 0x52, 0x47, 0x42, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x0f, 0x12, 0x18, 0x0a, 0x14, 0x52, 0x65, 0x63, 0x36, 0x30, 0x31, 0x4c, 0x75, 0x6d, 0x61, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x10, 0x12, 0x19, 0x0a, 0x15, 0x52, 0x65, 0x63, 0x36, 0x30, 0x31, 0x59, 0x43, 0x62, 0x43, 0x72, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x11, 0x12, 0x18, 0x0a, 0x14, 0x52, 0x65, 0x63, 0x37, 0x30, 0x39, 0x4c, 0x75, 0x6d, 0x61, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x12, 0x12, 0x19, 0x0a, 0x15, 0x52, 0x65, 0x63, 0x37, 0x30, 0x39, 0x59, 0x43, 0x62, 0x43, 0x72, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x70, 0x61, 0x63, 0x65, 0x10, 0x13, 0x42, 0x42, 0x5a, 0x40, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x67, 0x6f, 0x63, 0x76, 0x2f, 0x63, 0x67, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2d, 0x73, 0x70, 0x65, 0x63, 0x2f, 0x67, 0x6f, 0x63, 0x76, 0x3b, 0x67, 0x6f, 0x63, 0x76, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_gocv_gocv_magick_proto_rawDescOnce sync.Once file_gocv_gocv_magick_proto_rawDescData = file_gocv_gocv_magick_proto_rawDesc ) func file_gocv_gocv_magick_proto_rawDescGZIP() []byte { file_gocv_gocv_magick_proto_rawDescOnce.Do(func() { file_gocv_gocv_magick_proto_rawDescData = protoimpl.X.CompressGZIP(file_gocv_gocv_magick_proto_rawDescData) }) return file_gocv_gocv_magick_proto_rawDescData } var file_gocv_gocv_magick_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_gocv_gocv_magick_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_gocv_gocv_magick_proto_goTypes = []interface{}{ (OrientationType)(0), // 0: sdk.api.gocv.OrientationType (ColorspaceType)(0), // 1: sdk.api.gocv.ColorspaceType (*MagickInitializeMagickRequest)(nil), // 2: sdk.api.gocv.MagickInitializeMagickRequest (*MagickInitializeMagickResponse)(nil), // 3: sdk.api.gocv.MagickInitializeMagickResponse (*MagickImageDecodeRequest)(nil), // 4: sdk.api.gocv.MagickImageDecodeRequest (*MagickImageDecodeResponse)(nil), // 5: sdk.api.gocv.MagickImageDecodeResponse (*code.CgoError)(nil), // 6: sdk.types.code.CgoError } var file_gocv_gocv_magick_proto_depIdxs = []int32{ 6, // 0: sdk.api.gocv.MagickInitializeMagickResponse.error:type_name -> sdk.types.code.CgoError 6, // 1: sdk.api.gocv.MagickImageDecodeResponse.error:type_name -> sdk.types.code.CgoError 0, // 2: sdk.api.gocv.MagickImageDecodeResponse.orientation_type:type_name -> sdk.api.gocv.OrientationType 1, // 3: sdk.api.gocv.MagickImageDecodeResponse.colorspace_type:type_name -> sdk.api.gocv.ColorspaceType 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_gocv_gocv_magick_proto_init() } func file_gocv_gocv_magick_proto_init() { if File_gocv_gocv_magick_proto != nil { return } if !protoimpl.UnsafeEnabled { file_gocv_gocv_magick_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MagickInitializeMagickRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_gocv_gocv_magick_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MagickInitializeMagickResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_gocv_gocv_magick_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MagickImageDecodeRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_gocv_gocv_magick_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MagickImageDecodeResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_gocv_gocv_magick_proto_rawDesc, NumEnums: 2, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_gocv_gocv_magick_proto_goTypes, DependencyIndexes: file_gocv_gocv_magick_proto_depIdxs, EnumInfos: file_gocv_gocv_magick_proto_enumTypes, MessageInfos: file_gocv_gocv_magick_proto_msgTypes, }.Build() File_gocv_gocv_magick_proto = out.File file_gocv_gocv_magick_proto_rawDesc = nil file_gocv_gocv_magick_proto_goTypes = nil file_gocv_gocv_magick_proto_depIdxs = nil } ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/gocv/gocv.magick.pb.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: api/openapi-spec/gocv/gocv.magick.proto #ifndef PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto #define PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto #include #include #if GOOGLE_PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include #include #include #include #include #include #include #include #include // IWYU pragma: export #include // IWYU pragma: export #include #include #include "api/openapi-spec/types/code/sdk-go.code.pb.h" // @@protoc_insertion_point(includes) #define PROTOBUF_INTERNAL_EXPORT_protobuf_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto namespace protobuf_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto { // Internal implementation detail -- do not use these members. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[4]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; void AddDescriptors(); } // namespace protobuf_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto namespace sdk { namespace api { namespace gocv { class MagickImageDecodeRequest; class MagickImageDecodeRequestDefaultTypeInternal; extern MagickImageDecodeRequestDefaultTypeInternal _MagickImageDecodeRequest_default_instance_; class MagickImageDecodeResponse; class MagickImageDecodeResponseDefaultTypeInternal; extern MagickImageDecodeResponseDefaultTypeInternal _MagickImageDecodeResponse_default_instance_; class MagickInitializeMagickRequest; class MagickInitializeMagickRequestDefaultTypeInternal; extern MagickInitializeMagickRequestDefaultTypeInternal _MagickInitializeMagickRequest_default_instance_; class MagickInitializeMagickResponse; class MagickInitializeMagickResponseDefaultTypeInternal; extern MagickInitializeMagickResponseDefaultTypeInternal _MagickInitializeMagickResponse_default_instance_; } // namespace gocv } // namespace api } // namespace sdk namespace google { namespace protobuf { template<> ::sdk::api::gocv::MagickImageDecodeRequest* Arena::CreateMaybeMessage<::sdk::api::gocv::MagickImageDecodeRequest>(Arena*); template<> ::sdk::api::gocv::MagickImageDecodeResponse* Arena::CreateMaybeMessage<::sdk::api::gocv::MagickImageDecodeResponse>(Arena*); template<> ::sdk::api::gocv::MagickInitializeMagickRequest* Arena::CreateMaybeMessage<::sdk::api::gocv::MagickInitializeMagickRequest>(Arena*); template<> ::sdk::api::gocv::MagickInitializeMagickResponse* Arena::CreateMaybeMessage<::sdk::api::gocv::MagickInitializeMagickResponse>(Arena*); } // namespace protobuf } // namespace google namespace sdk { namespace api { namespace gocv { enum OrientationType { UndefinedOrientation = 0, TopLeftOrientation = 1, TopRightOrientation = 2, BottomRightOrientation = 3, BottomLeftOrientation = 4, LeftTopOrientation = 5, RightTopOrientation = 6, RightBottomOrientation = 7, LeftBottomOrientation = 8, OrientationType_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, OrientationType_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max }; bool OrientationType_IsValid(int value); const OrientationType OrientationType_MIN = UndefinedOrientation; const OrientationType OrientationType_MAX = LeftBottomOrientation; const int OrientationType_ARRAYSIZE = OrientationType_MAX + 1; const ::google::protobuf::EnumDescriptor* OrientationType_descriptor(); inline const ::std::string& OrientationType_Name(OrientationType value) { return ::google::protobuf::internal::NameOfEnum( OrientationType_descriptor(), value); } inline bool OrientationType_Parse( const ::std::string& name, OrientationType* value) { return ::google::protobuf::internal::ParseNamedEnum( OrientationType_descriptor(), name, value); } enum ColorspaceType { UndefinedColorspace = 0, RGBColorspace = 1, GRAYColorspace = 2, TransparentColorspace = 3, OHTAColorspace = 4, XYZColorspace = 5, YCCColorspace = 6, YIQColorspace = 7, YPbPrColorspace = 8, YUVColorspace = 9, CMYKColorspace = 10, sRGBColorspace = 11, HSLColorspace = 12, HWBColorspace = 13, LABColorspace = 14, CineonLogRGBColorspace = 15, Rec601LumaColorspace = 16, Rec601YCbCrColorspace = 17, Rec709LumaColorspace = 18, Rec709YCbCrColorspace = 19, ColorspaceType_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, ColorspaceType_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max }; bool ColorspaceType_IsValid(int value); const ColorspaceType ColorspaceType_MIN = UndefinedColorspace; const ColorspaceType ColorspaceType_MAX = Rec709YCbCrColorspace; const int ColorspaceType_ARRAYSIZE = ColorspaceType_MAX + 1; const ::google::protobuf::EnumDescriptor* ColorspaceType_descriptor(); inline const ::std::string& ColorspaceType_Name(ColorspaceType value) { return ::google::protobuf::internal::NameOfEnum( ColorspaceType_descriptor(), value); } inline bool ColorspaceType_Parse( const ::std::string& name, ColorspaceType* value) { return ::google::protobuf::internal::ParseNamedEnum( ColorspaceType_descriptor(), name, value); } // =================================================================== class MagickInitializeMagickRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:sdk.api.gocv.MagickInitializeMagickRequest) */ { public: MagickInitializeMagickRequest(); virtual ~MagickInitializeMagickRequest(); MagickInitializeMagickRequest(const MagickInitializeMagickRequest& from); inline MagickInitializeMagickRequest& operator=(const MagickInitializeMagickRequest& from) { CopyFrom(from); return *this; } #if LANG_CXX11 MagickInitializeMagickRequest(MagickInitializeMagickRequest&& from) noexcept : MagickInitializeMagickRequest() { *this = ::std::move(from); } inline MagickInitializeMagickRequest& operator=(MagickInitializeMagickRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const MagickInitializeMagickRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const MagickInitializeMagickRequest* internal_default_instance() { return reinterpret_cast( &_MagickInitializeMagickRequest_default_instance_); } static constexpr int kIndexInFileMessages = 0; void Swap(MagickInitializeMagickRequest* other); friend void swap(MagickInitializeMagickRequest& a, MagickInitializeMagickRequest& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline MagickInitializeMagickRequest* New() const final { return CreateMaybeMessage(NULL); } MagickInitializeMagickRequest* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MagickInitializeMagickRequest& from); void MergeFrom(const MagickInitializeMagickRequest& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MagickInitializeMagickRequest* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string path = 1; void clear_path(); static const int kPathFieldNumber = 1; const ::std::string& path() const; void set_path(const ::std::string& value); #if LANG_CXX11 void set_path(::std::string&& value); #endif void set_path(const char* value); void set_path(const char* value, size_t size); ::std::string* mutable_path(); ::std::string* release_path(); void set_allocated_path(::std::string* path); // @@protoc_insertion_point(class_scope:sdk.api.gocv.MagickInitializeMagickRequest) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr path_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto::TableStruct; }; // ------------------------------------------------------------------- class MagickInitializeMagickResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:sdk.api.gocv.MagickInitializeMagickResponse) */ { public: MagickInitializeMagickResponse(); virtual ~MagickInitializeMagickResponse(); MagickInitializeMagickResponse(const MagickInitializeMagickResponse& from); inline MagickInitializeMagickResponse& operator=(const MagickInitializeMagickResponse& from) { CopyFrom(from); return *this; } #if LANG_CXX11 MagickInitializeMagickResponse(MagickInitializeMagickResponse&& from) noexcept : MagickInitializeMagickResponse() { *this = ::std::move(from); } inline MagickInitializeMagickResponse& operator=(MagickInitializeMagickResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const MagickInitializeMagickResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const MagickInitializeMagickResponse* internal_default_instance() { return reinterpret_cast( &_MagickInitializeMagickResponse_default_instance_); } static constexpr int kIndexInFileMessages = 1; void Swap(MagickInitializeMagickResponse* other); friend void swap(MagickInitializeMagickResponse& a, MagickInitializeMagickResponse& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline MagickInitializeMagickResponse* New() const final { return CreateMaybeMessage(NULL); } MagickInitializeMagickResponse* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MagickInitializeMagickResponse& from); void MergeFrom(const MagickInitializeMagickResponse& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MagickInitializeMagickResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // .sdk.types.code.CgoError error = 1; bool has_error() const; void clear_error(); static const int kErrorFieldNumber = 1; private: const ::sdk::types::code::CgoError& _internal_error() const; public: const ::sdk::types::code::CgoError& error() const; ::sdk::types::code::CgoError* release_error(); ::sdk::types::code::CgoError* mutable_error(); void set_allocated_error(::sdk::types::code::CgoError* error); // @@protoc_insertion_point(class_scope:sdk.api.gocv.MagickInitializeMagickResponse) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::sdk::types::code::CgoError* error_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto::TableStruct; }; // ------------------------------------------------------------------- class MagickImageDecodeRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:sdk.api.gocv.MagickImageDecodeRequest) */ { public: MagickImageDecodeRequest(); virtual ~MagickImageDecodeRequest(); MagickImageDecodeRequest(const MagickImageDecodeRequest& from); inline MagickImageDecodeRequest& operator=(const MagickImageDecodeRequest& from) { CopyFrom(from); return *this; } #if LANG_CXX11 MagickImageDecodeRequest(MagickImageDecodeRequest&& from) noexcept : MagickImageDecodeRequest() { *this = ::std::move(from); } inline MagickImageDecodeRequest& operator=(MagickImageDecodeRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const MagickImageDecodeRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const MagickImageDecodeRequest* internal_default_instance() { return reinterpret_cast( &_MagickImageDecodeRequest_default_instance_); } static constexpr int kIndexInFileMessages = 2; void Swap(MagickImageDecodeRequest* other); friend void swap(MagickImageDecodeRequest& a, MagickImageDecodeRequest& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline MagickImageDecodeRequest* New() const final { return CreateMaybeMessage(NULL); } MagickImageDecodeRequest* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MagickImageDecodeRequest& from); void MergeFrom(const MagickImageDecodeRequest& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MagickImageDecodeRequest* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // bytes image = 1; void clear_image(); static const int kImageFieldNumber = 1; const ::std::string& image() const; void set_image(const ::std::string& value); #if LANG_CXX11 void set_image(::std::string&& value); #endif void set_image(const char* value); void set_image(const void* value, size_t size); ::std::string* mutable_image(); ::std::string* release_image(); void set_allocated_image(::std::string* image); // string target_color_space = 2; void clear_target_color_space(); static const int kTargetColorSpaceFieldNumber = 2; const ::std::string& target_color_space() const; void set_target_color_space(const ::std::string& value); #if LANG_CXX11 void set_target_color_space(::std::string&& value); #endif void set_target_color_space(const char* value); void set_target_color_space(const char* value, size_t size); ::std::string* mutable_target_color_space(); ::std::string* release_target_color_space(); void set_allocated_target_color_space(::std::string* target_color_space); // @@protoc_insertion_point(class_scope:sdk.api.gocv.MagickImageDecodeRequest) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr image_; ::google::protobuf::internal::ArenaStringPtr target_color_space_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto::TableStruct; }; // ------------------------------------------------------------------- class MagickImageDecodeResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:sdk.api.gocv.MagickImageDecodeResponse) */ { public: MagickImageDecodeResponse(); virtual ~MagickImageDecodeResponse(); MagickImageDecodeResponse(const MagickImageDecodeResponse& from); inline MagickImageDecodeResponse& operator=(const MagickImageDecodeResponse& from) { CopyFrom(from); return *this; } #if LANG_CXX11 MagickImageDecodeResponse(MagickImageDecodeResponse&& from) noexcept : MagickImageDecodeResponse() { *this = ::std::move(from); } inline MagickImageDecodeResponse& operator=(MagickImageDecodeResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const MagickImageDecodeResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const MagickImageDecodeResponse* internal_default_instance() { return reinterpret_cast( &_MagickImageDecodeResponse_default_instance_); } static constexpr int kIndexInFileMessages = 3; void Swap(MagickImageDecodeResponse* other); friend void swap(MagickImageDecodeResponse& a, MagickImageDecodeResponse& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline MagickImageDecodeResponse* New() const final { return CreateMaybeMessage(NULL); } MagickImageDecodeResponse* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MagickImageDecodeResponse& from); void MergeFrom(const MagickImageDecodeResponse& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MagickImageDecodeResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string magick = 5; void clear_magick(); static const int kMagickFieldNumber = 5; const ::std::string& magick() const; void set_magick(const ::std::string& value); #if LANG_CXX11 void set_magick(::std::string&& value); #endif void set_magick(const char* value); void set_magick(const char* value, size_t size); ::std::string* mutable_magick(); ::std::string* release_magick(); void set_allocated_magick(::std::string* magick); // .sdk.types.code.CgoError error = 1; bool has_error() const; void clear_error(); static const int kErrorFieldNumber = 1; private: const ::sdk::types::code::CgoError& _internal_error() const; public: const ::sdk::types::code::CgoError& error() const; ::sdk::types::code::CgoError* release_error(); ::sdk::types::code::CgoError* mutable_error(); void set_allocated_error(::sdk::types::code::CgoError* error); // int64 cv_mat_pointer = 2; void clear_cv_mat_pointer(); static const int kCvMatPointerFieldNumber = 2; ::google::protobuf::int64 cv_mat_pointer() const; void set_cv_mat_pointer(::google::protobuf::int64 value); // int64 rows = 3; void clear_rows(); static const int kRowsFieldNumber = 3; ::google::protobuf::int64 rows() const; void set_rows(::google::protobuf::int64 value); // int64 columns = 4; void clear_columns(); static const int kColumnsFieldNumber = 4; ::google::protobuf::int64 columns() const; void set_columns(::google::protobuf::int64 value); // .sdk.api.gocv.OrientationType orientation_type = 6; void clear_orientation_type(); static const int kOrientationTypeFieldNumber = 6; ::sdk::api::gocv::OrientationType orientation_type() const; void set_orientation_type(::sdk::api::gocv::OrientationType value); // .sdk.api.gocv.ColorspaceType colorspace_type = 7; void clear_colorspace_type(); static const int kColorspaceTypeFieldNumber = 7; ::sdk::api::gocv::ColorspaceType colorspace_type() const; void set_colorspace_type(::sdk::api::gocv::ColorspaceType value); // @@protoc_insertion_point(class_scope:sdk.api.gocv.MagickImageDecodeResponse) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr magick_; ::sdk::types::code::CgoError* error_; ::google::protobuf::int64 cv_mat_pointer_; ::google::protobuf::int64 rows_; ::google::protobuf::int64 columns_; int orientation_type_; int colorspace_type_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto::TableStruct; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // MagickInitializeMagickRequest // string path = 1; inline void MagickInitializeMagickRequest::clear_path() { path_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& MagickInitializeMagickRequest::path() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickInitializeMagickRequest.path) return path_.GetNoArena(); } inline void MagickInitializeMagickRequest::set_path(const ::std::string& value) { path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickInitializeMagickRequest.path) } #if LANG_CXX11 inline void MagickInitializeMagickRequest::set_path(::std::string&& value) { path_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sdk.api.gocv.MagickInitializeMagickRequest.path) } #endif inline void MagickInitializeMagickRequest::set_path(const char* value) { GOOGLE_DCHECK(value != NULL); path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sdk.api.gocv.MagickInitializeMagickRequest.path) } inline void MagickInitializeMagickRequest::set_path(const char* value, size_t size) { path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:sdk.api.gocv.MagickInitializeMagickRequest.path) } inline ::std::string* MagickInitializeMagickRequest::mutable_path() { // @@protoc_insertion_point(field_mutable:sdk.api.gocv.MagickInitializeMagickRequest.path) return path_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* MagickInitializeMagickRequest::release_path() { // @@protoc_insertion_point(field_release:sdk.api.gocv.MagickInitializeMagickRequest.path) return path_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void MagickInitializeMagickRequest::set_allocated_path(::std::string* path) { if (path != NULL) { } else { } path_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), path); // @@protoc_insertion_point(field_set_allocated:sdk.api.gocv.MagickInitializeMagickRequest.path) } // ------------------------------------------------------------------- // MagickInitializeMagickResponse // .sdk.types.code.CgoError error = 1; inline bool MagickInitializeMagickResponse::has_error() const { return this != internal_default_instance() && error_ != NULL; } inline const ::sdk::types::code::CgoError& MagickInitializeMagickResponse::_internal_error() const { return *error_; } inline const ::sdk::types::code::CgoError& MagickInitializeMagickResponse::error() const { const ::sdk::types::code::CgoError* p = error_; // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickInitializeMagickResponse.error) return p != NULL ? *p : *reinterpret_cast( &::sdk::types::code::_CgoError_default_instance_); } inline ::sdk::types::code::CgoError* MagickInitializeMagickResponse::release_error() { // @@protoc_insertion_point(field_release:sdk.api.gocv.MagickInitializeMagickResponse.error) ::sdk::types::code::CgoError* temp = error_; error_ = NULL; return temp; } inline ::sdk::types::code::CgoError* MagickInitializeMagickResponse::mutable_error() { if (error_ == NULL) { auto* p = CreateMaybeMessage<::sdk::types::code::CgoError>(GetArenaNoVirtual()); error_ = p; } // @@protoc_insertion_point(field_mutable:sdk.api.gocv.MagickInitializeMagickResponse.error) return error_; } inline void MagickInitializeMagickResponse::set_allocated_error(::sdk::types::code::CgoError* error) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == NULL) { delete reinterpret_cast< ::google::protobuf::MessageLite*>(error_); } if (error) { ::google::protobuf::Arena* submessage_arena = NULL; if (message_arena != submessage_arena) { error = ::google::protobuf::internal::GetOwnedMessage( message_arena, error, submessage_arena); } } else { } error_ = error; // @@protoc_insertion_point(field_set_allocated:sdk.api.gocv.MagickInitializeMagickResponse.error) } // ------------------------------------------------------------------- // MagickImageDecodeRequest // bytes image = 1; inline void MagickImageDecodeRequest::clear_image() { image_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& MagickImageDecodeRequest::image() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeRequest.image) return image_.GetNoArena(); } inline void MagickImageDecodeRequest::set_image(const ::std::string& value) { image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickImageDecodeRequest.image) } #if LANG_CXX11 inline void MagickImageDecodeRequest::set_image(::std::string&& value) { image_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sdk.api.gocv.MagickImageDecodeRequest.image) } #endif inline void MagickImageDecodeRequest::set_image(const char* value) { GOOGLE_DCHECK(value != NULL); image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sdk.api.gocv.MagickImageDecodeRequest.image) } inline void MagickImageDecodeRequest::set_image(const void* value, size_t size) { image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:sdk.api.gocv.MagickImageDecodeRequest.image) } inline ::std::string* MagickImageDecodeRequest::mutable_image() { // @@protoc_insertion_point(field_mutable:sdk.api.gocv.MagickImageDecodeRequest.image) return image_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* MagickImageDecodeRequest::release_image() { // @@protoc_insertion_point(field_release:sdk.api.gocv.MagickImageDecodeRequest.image) return image_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void MagickImageDecodeRequest::set_allocated_image(::std::string* image) { if (image != NULL) { } else { } image_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), image); // @@protoc_insertion_point(field_set_allocated:sdk.api.gocv.MagickImageDecodeRequest.image) } // string target_color_space = 2; inline void MagickImageDecodeRequest::clear_target_color_space() { target_color_space_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& MagickImageDecodeRequest::target_color_space() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeRequest.target_color_space) return target_color_space_.GetNoArena(); } inline void MagickImageDecodeRequest::set_target_color_space(const ::std::string& value) { target_color_space_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickImageDecodeRequest.target_color_space) } #if LANG_CXX11 inline void MagickImageDecodeRequest::set_target_color_space(::std::string&& value) { target_color_space_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sdk.api.gocv.MagickImageDecodeRequest.target_color_space) } #endif inline void MagickImageDecodeRequest::set_target_color_space(const char* value) { GOOGLE_DCHECK(value != NULL); target_color_space_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sdk.api.gocv.MagickImageDecodeRequest.target_color_space) } inline void MagickImageDecodeRequest::set_target_color_space(const char* value, size_t size) { target_color_space_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:sdk.api.gocv.MagickImageDecodeRequest.target_color_space) } inline ::std::string* MagickImageDecodeRequest::mutable_target_color_space() { // @@protoc_insertion_point(field_mutable:sdk.api.gocv.MagickImageDecodeRequest.target_color_space) return target_color_space_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* MagickImageDecodeRequest::release_target_color_space() { // @@protoc_insertion_point(field_release:sdk.api.gocv.MagickImageDecodeRequest.target_color_space) return target_color_space_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void MagickImageDecodeRequest::set_allocated_target_color_space(::std::string* target_color_space) { if (target_color_space != NULL) { } else { } target_color_space_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), target_color_space); // @@protoc_insertion_point(field_set_allocated:sdk.api.gocv.MagickImageDecodeRequest.target_color_space) } // ------------------------------------------------------------------- // MagickImageDecodeResponse // .sdk.types.code.CgoError error = 1; inline bool MagickImageDecodeResponse::has_error() const { return this != internal_default_instance() && error_ != NULL; } inline const ::sdk::types::code::CgoError& MagickImageDecodeResponse::_internal_error() const { return *error_; } inline const ::sdk::types::code::CgoError& MagickImageDecodeResponse::error() const { const ::sdk::types::code::CgoError* p = error_; // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeResponse.error) return p != NULL ? *p : *reinterpret_cast( &::sdk::types::code::_CgoError_default_instance_); } inline ::sdk::types::code::CgoError* MagickImageDecodeResponse::release_error() { // @@protoc_insertion_point(field_release:sdk.api.gocv.MagickImageDecodeResponse.error) ::sdk::types::code::CgoError* temp = error_; error_ = NULL; return temp; } inline ::sdk::types::code::CgoError* MagickImageDecodeResponse::mutable_error() { if (error_ == NULL) { auto* p = CreateMaybeMessage<::sdk::types::code::CgoError>(GetArenaNoVirtual()); error_ = p; } // @@protoc_insertion_point(field_mutable:sdk.api.gocv.MagickImageDecodeResponse.error) return error_; } inline void MagickImageDecodeResponse::set_allocated_error(::sdk::types::code::CgoError* error) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == NULL) { delete reinterpret_cast< ::google::protobuf::MessageLite*>(error_); } if (error) { ::google::protobuf::Arena* submessage_arena = NULL; if (message_arena != submessage_arena) { error = ::google::protobuf::internal::GetOwnedMessage( message_arena, error, submessage_arena); } } else { } error_ = error; // @@protoc_insertion_point(field_set_allocated:sdk.api.gocv.MagickImageDecodeResponse.error) } // int64 cv_mat_pointer = 2; inline void MagickImageDecodeResponse::clear_cv_mat_pointer() { cv_mat_pointer_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 MagickImageDecodeResponse::cv_mat_pointer() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeResponse.cv_mat_pointer) return cv_mat_pointer_; } inline void MagickImageDecodeResponse::set_cv_mat_pointer(::google::protobuf::int64 value) { cv_mat_pointer_ = value; // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickImageDecodeResponse.cv_mat_pointer) } // int64 rows = 3; inline void MagickImageDecodeResponse::clear_rows() { rows_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 MagickImageDecodeResponse::rows() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeResponse.rows) return rows_; } inline void MagickImageDecodeResponse::set_rows(::google::protobuf::int64 value) { rows_ = value; // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickImageDecodeResponse.rows) } // int64 columns = 4; inline void MagickImageDecodeResponse::clear_columns() { columns_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 MagickImageDecodeResponse::columns() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeResponse.columns) return columns_; } inline void MagickImageDecodeResponse::set_columns(::google::protobuf::int64 value) { columns_ = value; // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickImageDecodeResponse.columns) } // string magick = 5; inline void MagickImageDecodeResponse::clear_magick() { magick_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& MagickImageDecodeResponse::magick() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeResponse.magick) return magick_.GetNoArena(); } inline void MagickImageDecodeResponse::set_magick(const ::std::string& value) { magick_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickImageDecodeResponse.magick) } #if LANG_CXX11 inline void MagickImageDecodeResponse::set_magick(::std::string&& value) { magick_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sdk.api.gocv.MagickImageDecodeResponse.magick) } #endif inline void MagickImageDecodeResponse::set_magick(const char* value) { GOOGLE_DCHECK(value != NULL); magick_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sdk.api.gocv.MagickImageDecodeResponse.magick) } inline void MagickImageDecodeResponse::set_magick(const char* value, size_t size) { magick_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:sdk.api.gocv.MagickImageDecodeResponse.magick) } inline ::std::string* MagickImageDecodeResponse::mutable_magick() { // @@protoc_insertion_point(field_mutable:sdk.api.gocv.MagickImageDecodeResponse.magick) return magick_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* MagickImageDecodeResponse::release_magick() { // @@protoc_insertion_point(field_release:sdk.api.gocv.MagickImageDecodeResponse.magick) return magick_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void MagickImageDecodeResponse::set_allocated_magick(::std::string* magick) { if (magick != NULL) { } else { } magick_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), magick); // @@protoc_insertion_point(field_set_allocated:sdk.api.gocv.MagickImageDecodeResponse.magick) } // .sdk.api.gocv.OrientationType orientation_type = 6; inline void MagickImageDecodeResponse::clear_orientation_type() { orientation_type_ = 0; } inline ::sdk::api::gocv::OrientationType MagickImageDecodeResponse::orientation_type() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeResponse.orientation_type) return static_cast< ::sdk::api::gocv::OrientationType >(orientation_type_); } inline void MagickImageDecodeResponse::set_orientation_type(::sdk::api::gocv::OrientationType value) { orientation_type_ = value; // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickImageDecodeResponse.orientation_type) } // .sdk.api.gocv.ColorspaceType colorspace_type = 7; inline void MagickImageDecodeResponse::clear_colorspace_type() { colorspace_type_ = 0; } inline ::sdk::api::gocv::ColorspaceType MagickImageDecodeResponse::colorspace_type() const { // @@protoc_insertion_point(field_get:sdk.api.gocv.MagickImageDecodeResponse.colorspace_type) return static_cast< ::sdk::api::gocv::ColorspaceType >(colorspace_type_); } inline void MagickImageDecodeResponse::set_colorspace_type(::sdk::api::gocv::ColorspaceType value) { colorspace_type_ = value; // @@protoc_insertion_point(field_set:sdk.api.gocv.MagickImageDecodeResponse.colorspace_type) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace gocv } // namespace api } // namespace sdk namespace google { namespace protobuf { template <> struct is_proto_enum< ::sdk::api::gocv::OrientationType> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::sdk::api::gocv::OrientationType>() { return ::sdk::api::gocv::OrientationType_descriptor(); } template <> struct is_proto_enum< ::sdk::api::gocv::ColorspaceType> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::sdk::api::gocv::ColorspaceType>() { return ::sdk::api::gocv::ColorspaceType_descriptor(); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2fgocv_2fgocv_2emagick_2eproto ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/gocv/gocv.magick.proto ================================================ syntax = "proto3"; package sdk.api.gocv; import "api/openapi-spec/types/code/sdk-go.code.proto"; option go_package = "github.com/kaydxh/golang/pkg/gocv/cgo/api/openapi-spec/gocv;gocv"; message MagickInitializeMagickRequest { string path = 1; } message MagickInitializeMagickResponse { sdk.types.code.CgoError error = 1; } message MagickImageDecodeRequest { bytes image = 1; string target_color_space = 2; // support BGR BGRA GRA GRAYA, default BGRA } message MagickImageDecodeResponse { sdk.types.code.CgoError error = 1; int64 cv_mat_pointer = 2; // pointer of cv::Mat int64 rows = 3; // Image height int64 columns = 4; // Image width string magick = 5; // File type magick identifier (.e.g "GIF") OrientationType orientation_type = 6; ColorspaceType colorspace_type = 7; } enum OrientationType { UndefinedOrientation = 0; TopLeftOrientation = 1; TopRightOrientation = 2; BottomRightOrientation = 3; BottomLeftOrientation = 4; LeftTopOrientation = 5; RightTopOrientation = 6; RightBottomOrientation = 7; LeftBottomOrientation = 8; } // graphics-magick/include/magick/colorspace.h enum ColorspaceType { UndefinedColorspace = 0; RGBColorspace = 1; /* Plain old RGB colorspace */ GRAYColorspace = 2; /* Plain old full-range grayscale */ TransparentColorspace = 3; /* RGB but preserve matte channel during quantize */ OHTAColorspace = 4; XYZColorspace = 5; /* CIE XYZ */ YCCColorspace = 6; /* Kodak PhotoCD PhotoYCC */ YIQColorspace = 7; YPbPrColorspace = 8; YUVColorspace = 9; CMYKColorspace = 10; /* Cyan, magenta, yellow, black, alpha */ sRGBColorspace = 11; /* Kodak PhotoCD sRGB */ HSLColorspace = 12; /* Hue, saturation, luminosity */ HWBColorspace = 13; /* Hue, whiteness, blackness */ LABColorspace = 14; /* LAB colorspace not supported yet other than via lcms */ CineonLogRGBColorspace = 15; /* RGB data with Cineon Log scaling, 2.048 density range */ Rec601LumaColorspace = 16; /* Luma (Y) according to ITU-R 601 */ Rec601YCbCrColorspace = 17; /* YCbCr according to ITU-R 601 */ Rec709LumaColorspace = 18; /* Luma (Y) according to ITU-R 709 */ Rec709YCbCrColorspace = 19; /* YCbCr according to ITU-R 709 */ } ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/proto.gen.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 openapispec //go:generate mkdir -p ./scripts //go:generate bash -c "curl -s -L -o ./scripts/proto-gen.sh https://raw.githubusercontent.com/kaydxh/golang/main/script/go_proto_gen.sh" //go:generate bash scripts/proto-gen.sh --proto_file_path . -I . -I ../../ --third_party_path ../../../../../third_party --with-go ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/scripts/proto-gen.sh ================================================ # Created by kayxhding on 2020-10-11 12:40:37 #!/usr/bin/env bash # exit by command return non-zero exit code set -o errexit # Indicate an error when it encounters an undefined variable set -o nounset # Fail on any error. set -o pipefail #set -o xtrace # example, generate golang proto files # bash go_proto_gen.sh -I . --proto_file_path pkg/webserver/webserver.proto --with-go # if script called by source, $0 is the name of father script, not the name of source run script SCRIPT_PATH=$(cd `dirname "${BASH_SOURCE[0]}"`;pwd) <<'COMMENT' SCRIPT=$(readlink -f "${BASH_SOURCE[0]}") SCRIPT_PATH=$(dirname "$SCRIPT") echo ${SCRIPT_PATH} COMMENT PROTOC_FILE_DIR= PROTO_HEADERS= # THIRD_PARTY_DIR=$(realpath "${2:-${SCRIPT_PATH}/../../third_party}") THIRD_PARTY_DIR="${SCRIPT_PATH}/third_party" WITH_DOC= WITH_CPP= WITH_GO= function die() { echo 1>&2 "$*" exit 1 } function getopts() { local -a protodirs while test $# -ne 0 do case "$1" in -I|--proto_path) protodirs+=( "-I $(realpath "$2")" ) shift ;; --third_party_path) THIRD_PARTY_DIR=$(realpath "$2") shift ;; --with-doc) WITH_DOC=1 ;; --proto_file_path) PROTOC_FILE_DIR=$(realpath "$2") shift ;; --with-cpp) WITH_CPP=1 ;; --with-go) WITH_GO=1 ;; esac shift done PROTO_HEADERS="${protodirs[*]}" # echo "${protodirs[*]}" } <<'COMMENT' # This will place three binaries in your $GOBIN # Make sure that your $GOBIN is in your $PATH # install protoc-gen-doc on mac=> https: # github.com/pseudomuto/protoc-gen-doc/issues/20 (make build, cp bin/protoc-gen-doc ${GOBIN}) go install \ github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \ github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 \ google.golang.org/protobuf/cmd/protoc-gen-go \ google.golang.org/grpc/cmd/protoc-gen-go-grpc \ github.com/pseudomuto/protoc-gen-doc/cmd/protoc-gen-doc \ github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger COMMENT echo `pwd` getopts $@ echo "==> Checking tools..." #GEN_PROTO_TOOLS=(protoc protoc-gen-go protoc-gen-grpc-gateway protoc-gen-govalidators) GEN_PROTO_TOOLS=(protoc protoc-gen-go protoc-gen-grpc-gateway) for tool in ${GEN_PROTO_TOOLS[@]}; do q=$(command -v ${tool}) || die "didn't find ${tool}" echo 1>&2 "${tool}: ${q}" done echo "==> Generating proto..." #proto_headers="-I ${SCRIPT_PATH}/../../third_party" #proto_headers="-I .. -I ${THIRD_PARTY_DIR}" # "-I ." need behind PROTO_HEADERS, or remove it proto_headers="${PROTO_HEADERS} -I `pwd`" proto_headers="${proto_headers} -I ${THIRD_PARTY_DIR}/github.com/grpc-ecosystem/grpc-gateway" source_relative_option="paths=source_relative:." go_opt_option="" go_out_option="" go_tag_option="" go_grpc_option="" doc_option="" doc_out_option="" cpp_option="" cpp_out_option="" cpp_grpc_option="" grpc_gateway_option="" grpc_gateway_out_option="--grpc-gateway_out=logtostderr=true" grpc_gateway_delete_option="--grpc-gateway_opt=allow_delete_body=true" for proto in $(find ${PROTOC_FILE_DIR} -type f -name '*.proto' -print0 | xargs -0); do echo "Generating ${proto}" proto_base_name="$(basename ${proto} .proto)" api_conf_yaml_base_name="${proto_base_name}.yaml" api_conf_yaml_dir="$(dirname ${proto})" api_conf_yaml="${api_conf_yaml_dir}/$api_conf_yaml_base_name" grpc_api_yaml_option="" grpc_gateway_option="" if [[ -f "${api_conf_yaml}" ]];then grpc_api_yaml_option="grpc_api_configuration=${api_conf_yaml},${source_relative_option}" grpc_gateway_option="${grpc_gateway_out_option},${grpc_api_yaml_option} ${grpc_gateway_delete_option}" fi if [[ "${WITH_DOC}" -eq 1 ]]; then # output file name doc_option="--doc_opt=markdown,${proto_base_name}.md" doc_out_option="--doc_out=${SCRIPT_PATH}/../doc" fi if [[ "${WITH_CPP}" -eq 1 ]]; then cpp_option="--cpp_out=." cpp_out_option="--grpc_out=." cpp_grpc_option="--plugin=protoc-gen-grpc=`which grpc_cpp_plugin`" fi if [[ "${WITH_GO}" -eq 1 ]]; then # go_tag_option="--go-tag_out=${source_relative_option}" go_out_option="--go_out=." go_opt_option="--go_opt=paths=source_relative" go_grpc_option="--go-grpc_out=${source_relative_option}" fi protoc ${proto_headers} ${go_out_option} ${go_tag_option} ${go_opt_option} ${go_grpc_option} ${grpc_gateway_option} ${cpp_out_option} ${cpp_option} ${doc_option} ${doc_out_option} ${cpp_grpc_option} "${proto}" #protoc -I . ${proto_headers} --go-tag_out=paths=source_relative:. --go-grpc_out=paths=source_relative:. --grpc-gateway_out=logtostderr=true,grpc_api_configuration=${api_conf_yaml},paths=source_relative:. --grpc-gateway_opt=allow_delete_body=true ${f} done ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/thirdparty.cmake ================================================ cmake_minimum_required(VERSION 2.8) macro(log_debug msg) get_filename_component(name ${CMAKE_CURRENT_LIST_FILE} NAME) string(TIMESTAMP TIME_NOW "%Y-%m-%d %H:%M:%S") message("${TIME_NOW} - ${name}:${CMAKE_CURRENT_LIST_LINE} - ${msg}") endmacro(log_debug) macro(log_warn msg) get_filename_component(name ${CMAKE_CURRENT_LIST_FILE} NAME) string(TIMESTAMP TIME_NOW "%Y-%m-%d %H:%M:%S") message(WARNING "${TIME_NOW} - ${name}:${CMAKE_CURRENT_LIST_LINE} - ${msg}") endmacro(log_warn) macro(log_error msg) get_filename_component(name ${CMAKE_CURRENT_LIST_FILE} NAME) string(TIMESTAMP TIME_NOW "%Y-%m-%d %H:%M:%S") message(SEND_ERROR "${TIME_NOW} - ${name}:${CMAKE_CURRENT_LIST_LINE} - ${msg}") endmacro(log_error) macro(debug_vars) FOREACH(A ${ARGN}) log_debug("${A}:${${A}}") ENDFOREACH(A) endmacro(debug_vars) macro(log_execute_process) set(options "" ) set(oneValueArgs WORKING_DIRECTORY ) set(multiValueArgs COMMAND) cmake_parse_arguments(log_execute_process "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) string(REPLACE ";" " " CMD "${log_execute_process_COMMAND}") if(NOT log_execute_process_WORKING_DIRECTORY) log_error("bad cmd:cd ${log_execute_process_WORKING_DIRECTORY} && ${CMD}") endif() if(NOT EXISTS ${log_execute_process_WORKING_DIRECTORY}) log_error("bad cmd:cd ${log_execute_process_WORKING_DIRECTORY} && ${CMD}") endif() log_debug("cd ${log_execute_process_WORKING_DIRECTORY} && ${CMD}") execute_process(COMMAND ${log_execute_process_COMMAND} WORKING_DIRECTORY ${log_execute_process_WORKING_DIRECTORY} RESULT_VARIABLE rv ERROR_VARIABLE er OUTPUT_FILE ${log_execute_process_WORKING_DIRECTORY}/out.log ERROR_FILE ${log_execute_process_WORKING_DIRECTORY}/error.log) if(rv) log_debug("RESULT:${rv}, ERROR:${er}") endif() endmacro(log_execute_process) macro(add_files_to_qtcreator DIR) get_filename_component(dir_name ${DIR} NAME) string(REGEX REPLACE "/" "_" source_target ${DIR}) set(source_target "${dir_name}_${source_target}") log_debug("add_files_to_qtcreator: ${source_target}") set(files_sources "") foreach(fileprex ${ARGN}) file(GLOB_RECURSE _src_files RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${DIR}/*${fileprex}) foreach(src_file ${_src_files}) if(NOT (src_file MATCHES ".*\\.git.*")) list(APPEND files_sources ${src_file}) endif() endforeach() endforeach() add_custom_target(${source_target} SOURCES ${files_sources} WORKING_DIRECTORY ${DIR}) endmacro(add_files_to_qtcreator) macro(add_shared_library DIR) set_property(GLOBAL APPEND PROPERTY GLOBAL_INCLUDE_DIRS "${DIR}/include") SET(LIB_DIR ${DIR}/lib) if(NOT EXISTS ${LIB_DIR}) SET(LIB_DIR ${DIR}/lib64) endif() set_property(GLOBAL APPEND PROPERTY GLOBAL_LINK_DIRS ${LIB_DIR}) INCLUDE_DIRECTORIES(${DIR}/include) add_files_to_qtcreator(${DIR}/include .h .hpp) foreach(libname ${ARGN}) add_library(${libname} SHARED IMPORTED) set_property(TARGET ${libname} PROPERTY IMPORTED_LOCATION ${DIR}/lib/lib${libname}.so) set(SHARED_SO_PATH ${SHARED_SO_PATH}:${DIR}/lib) endforeach() log_debug("add_shared_library: ${ARGN} in: ${DIR}") endmacro(add_shared_library) macro(add_static_library DIR) set_property(GLOBAL APPEND PROPERTY GLOBAL_INCLUDE_DIRS "${DIR}/include") SET(LIB_DIR ${DIR}/lib) if(NOT EXISTS ${LIB_DIR}) SET(LIB_DIR ${DIR}/lib64) endif() set_property(GLOBAL APPEND PROPERTY GLOBAL_LINK_DIRS ${LIB_DIR}) INCLUDE_DIRECTORIES(${DIR}/include) add_files_to_qtcreator(${DIR}/include .h .hpp) foreach(libname ${ARGN}) add_library(${libname} STATIC IMPORTED) set_property(TARGET ${libname} PROPERTY IMPORTED_LOCATION ${DIR}/lib/lib${libname}.a) endforeach() log_debug("add_static_library: ${ARGN} in: ${DIR}") endmacro(add_static_library) MACRO(SUBDIRLIST result curdir) FILE(GLOB children RELATIVE ${curdir} ${curdir}/[a-zA-Z0-9]*) SET(dirlist "") FOREACH(child ${children}) IF(IS_DIRECTORY ${curdir}/${child}) LIST(APPEND dirlist ${child}) ENDIF() ENDFOREACH() SET(${result} ${dirlist}) ENDMACRO() MACRO(SUBLIBLIST shared_result static_result curdir) FILE(GLOB children RELATIVE ${curdir} ${curdir}/lib*.so) SET(filelist "") FOREACH(child ${children}) IF(IS_DIRECTORY ${curdir}/${child}) ELSE(IS_DIRECTORY ${curdir}/${child}) LIST(APPEND filelist ${child}) ENDIF() ENDFOREACH() SET(${shared_result} ${filelist}) FILE(GLOB children RELATIVE ${curdir} ${curdir}/lib*.a) SET(filelist "") FOREACH(child ${children}) IF(IS_DIRECTORY ${curdir}/${child}) ELSE(IS_DIRECTORY ${curdir}/${child}) LIST(APPEND filelist ${child}) ENDIF() ENDFOREACH() SET(${static_result} ${filelist}) ENDMACRO() MACRO(IMPORT_ONE_LIB DEP_DIR) SET(DEP_LIBDIR ${DEP_DIR}/lib) if(NOT EXISTS ${DEP_LIBDIR}) SET(DEP_LIBDIR ${DEP_DIR}/lib64) endif() SUBLIBLIST(SHARED_LIBS STATIC_LIBS ${DEP_LIBDIR}) list(LENGTH SHARED_LIBS shared_count) list(LENGTH STATIC_LIBS static_count) message(STATUS "${dep} shared_count : ${shared_count}") message(STATUS "${dep} static_count : ${static_count}") INCLUDE_DIRECTORIES(${DEP_DIR}/include) set_property(GLOBAL APPEND PROPERTY GLOBAL_INCLUDE_DIRS "${DEP_DIR}/include") set_property(GLOBAL APPEND PROPERTY GLOBAL_LINK_DIRS ${DEP_LIBDIR}) set(mkl_regex ".*mkl.*") if (${shared_count} STREQUAL "0") if (${static_count} STREQUAL "0") message(STATUS "${DEP_DIR} has no lib to import") else (${static_count} STREQUAL "0") FILE(GLOB children RELATIVE ${DEP_LIBDIR} ${DEP_LIBDIR}/lib*.a) foreach(libs ${children}) string(REGEX REPLACE "^lib" "" _lib_name ${libs}) string(REGEX REPLACE "\\.a" "" _lib_name ${_lib_name}) if(TARGET ${_lib_name}) get_property(_lib_name_dir TARGET ${_lib_name} PROPERTY IMPORTED_LOCATION) log_warn("${_lib_name} already add at:${_lib_name_dir} skip ${DEP_LIBDIR}/${libs}") continue() endif() add_library(${_lib_name} STATIC IMPORTED) set_property(TARGET ${_lib_name} PROPERTY IMPORTED_LOCATION ${DEP_LIBDIR}/${libs}) log_debug("SET ${_lib_name}: ${DEP_LIBDIR}/${libs}") endforeach() endif() else (${shared_count} STREQUAL "0") FILE(GLOB children RELATIVE ${DEP_LIBDIR} ${DEP_LIBDIR}/lib*.so) foreach(libs ${children}) string(REGEX REPLACE "^lib" "" _lib_name ${libs}) string(REGEX REPLACE "\\.so" "" _lib_name ${_lib_name}) if(TARGET ${_lib_name}) get_property(_lib_name_dir TARGET ${_lib_name} PROPERTY IMPORTED_LOCATION) log_warn("${_lib_name} already add at:${_lib_name_dir} skip ${DEP_LIBDIR}/${libs}") continue() endif() add_library(${_lib_name} SHARED IMPORTED) set_property(TARGET ${_lib_name} PROPERTY IMPORTED_LOCATION ${DEP_LIBDIR}/${libs}) log_debug("SET ${_lib_name}: ${DEP_LIBDIR}/${libs}") if ("${_lib_name}" MATCHES "${mkl_regex}") log_debug("${_lib_name}: IMPORTED_NO_SONAME") set_property(TARGET ${_lib_name} PROPERTY IMPORTED_NO_SONAME 1) endif() endforeach() endif() ENDMACRO() MACRO(ADD_THIRD_LIB THIRD_PATH) SUBDIRLIST(SUB_THIRD_DIRS ${THIRD_PATH}) message(STATUS "SUB_THIRD_LIBS: ${SUB_THIRD_DIRS}") set(cuda8_regex ".*cuda8.*") set(cuda9_regex ".*cuda9.*") set(cuda10_regex ".*cuda10.*") foreach(dep ${SUB_THIRD_DIRS}) message(STATUS "dep: ${dep}") if("${dep}" MATCHES "${cuda8_regex}") if(${CUDA8_0}) message(STATUS "add ${THIRD_PATH}/${deps}") IMPORT_ONE_LIB(${THIRD_PATH}/${dep}) set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -Xcompiler -fPIC -O3 --compiler-options -fno-strict-aliasing -lineinfo -Xptxas -dlcm=cg -use_fast_math -gencode arch=compute_61,code=sm_61 -gencode arch=compute_60,code=sm_60 -gencode arch=compute_52,code=sm_52" CACHE STRING "cuda flags") message(STATUS "CUDA_NVCC_FLAGS:${CUDA_NVCC_FLAGS}") endif(${CUDA8_0}) elseif("${dep}" MATCHES "${cuda9_regex}") if(${CUDA9_0}) message(STATUS "add ${THIRD_PATH}/${deps}") IMPORT_ONE_LIB(${THIRD_PATH}/${dep}) set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -Xcompiler -fPIC -O3 --compiler-options -fno-strict-aliasing -lineinfo -Xptxas -dlcm=cg -use_fast_math -gencode arch=compute_70,code=sm_70 -gencode arch=compute_61,code=sm_61 -gencode arch=compute_60,code=sm_60 -gencode arch=compute_52,code=sm_52" CACHE STRING "cuda flags") message(STATUS "CUDA_NVCC_FLAGS:${CUDA_NVCC_FLAGS}") endif(${CUDA9_0}) elseif("${dep}" MATCHES "${cuda10_regex}") if(${CUDA10_0}) message(STATUS "add ${THIRD_PATH}/${deps}") IMPORT_ONE_LIB(${THIRD_PATH}/${dep}) set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -Xcompiler -fPIC -O3 --compiler-options -fno-strict-aliasing -lineinfo -Xptxas -dlcm=cg -use_fast_math -gencode arch=compute_75,code=sm_75 -gencode arch=compute_70,code=sm_70 -gencode arch=compute_61,code=sm_61 -gencode arch=compute_60,code=sm_60 -gencode arch=compute_52,code=sm_52" CACHE STRING "cuda flags") message(STATUS "CUDA_NVCC_FLAGS:${CUDA_NVCC_FLAGS}") endif(${CUDA10_0}) else("${dep}" MATCHES "${cuda8_regex}") message(STATUS "not cuda8 or cuda9 lib. normal import") IMPORT_ONE_LIB(${THIRD_PATH}/${dep}) endif("${dep}" MATCHES "${cuda8_regex}") endforeach() ENDMACRO() # Usage in your CMakeLists: # Describe property define_property(GLOBAL PROPERTY GLOBAL_INCLUDE_DIRS BRIEF_DOCS "GLOBAL_INCLUDE_DIRS" FULL_DOCS "GLOBAL_INCLUDE_DIRS") define_property(GLOBAL PROPERTY GLOBAL_LINK_DIRS BRIEF_DOCS "GLOBAL_LINK_DIRS" FULL_DOCS "GLOBAL_LINK_DIRS") # Initialize property set_property(GLOBAL PROPERTY GLOBAL_INCLUDE_DIRS "") set_property(GLOBAL PROPERTY GLOBAL_LINK_DIRS "") #build type #flag to import CUDA8.0/9.0/10.0 option(BUILD_CUDA8_0 "BUILD_CUDA8_0" OFF) set(CUDA8_0 FALSE) if(BUILD_CUDA8_0) set(CUDA8_0 TRUE) endif(BUILD_CUDA8_0) option(BUILD_CUDA9_0 "BUILD_CUDA9_0" OFF) set(CUDA9_0 FALSE) if(BUILD_CUDA9_0) set(CUDA9_0 TRUE) endif(BUILD_CUDA9_0) option(BUILD_CUDA10_0 "BUILD_CUDA10_0" OFF) set(CUDA10_0 FALSE) if(BUILD_CUDA10_0) set(CUDA10_0 TRUE) endif(BUILD_CUDA10_0) set(THIRD_PATH ${CMAKE_SOURCE_DIR}/third_path) if(NOT EXISTS ${THIRD_PATH}) set(THIRD_PATH ${CMAKE_SOURCE_DIR}/../third_path) endif() message(STATUS "THIRD_PATH;${THIRD_PATH}") ADD_THIRD_LIB(${THIRD_PATH}) IF(CUDA8_0) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda8_0) include(FindCUDA) message(STATUS "FindCUDA - CUDA_TOOLKIT_ROOT_DIR: ${THIRD_PATH}/cuda8_0; ") ELSE(CUDA8_0) IF(IS_DIRECTORY ${THIRD_PATH}/cuda) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda) include(FindCUDA) ELSE(IS_DIRECTORY ${THIRD_PATH}/cuda) ENDIF() ENDIF() IF(CUDA9_0) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda9_0) include(FindCUDA) message(STATUS "FindCUDA - CUDA_TOOLKIT_ROOT_DIR: ${THIRD_PATH}/cuda9_0; ") ELSE(CUDA9_0) IF(IS_DIRECTORY ${THIRD_PATH}/cuda) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda) include(FindCUDA) ELSE(IS_DIRECTORY ${THIRD_PATH}/cuda) ENDIF() ENDIF() IF(CUDA10_0) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda10_0) include(FindCUDA) message(STATUS "FindCUDA - CUDA_TOOLKIT_ROOT_DIR: ${THIRD_PATH}/cuda10_0; ") ELSE(CUDA10_0) IF(IS_DIRECTORY ${THIRD_PATH}/cuda) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda) include(FindCUDA) ELSE(IS_DIRECTORY ${THIRD_PATH}/cuda) ENDIF() ENDIF() # Get property get_property(GLOBAL_INCLUDE_DIRS_LIST GLOBAL PROPERTY GLOBAL_INCLUDE_DIRS) get_property(GLOBAL_LINK_DIRS_LIST GLOBAL PROPERTY GLOBAL_LINK_DIRS) INCLUDE_DIRECTORIES(${GLOBAL_INCLUDE_DIRS_LIST}) LINK_DIRECTORIES(${GLOBAL_LINK_DIRS_LIST}) ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/thirdparty.srv.cmake ================================================ include(CMakeParseArguments) # # log_execute_process is same to execute_process but message cmd to log # macro(log_debug msg) get_filename_component(name ${CMAKE_CURRENT_LIST_FILE} NAME) string(TIMESTAMP TIME_NOW "%Y-%m-%d %H:%M:%S") message("${TIME_NOW} - ${name}:${CMAKE_CURRENT_LIST_LINE} - ${msg}") endmacro(log_debug) macro(log_warn msg) get_filename_component(name ${CMAKE_CURRENT_LIST_FILE} NAME) string(TIMESTAMP TIME_NOW "%Y-%m-%d %H:%M:%S") message(WARNING "${TIME_NOW} - ${name}:${CMAKE_CURRENT_LIST_LINE} - ${msg}") endmacro(log_warn) # macro(log_error msg) get_filename_component(name ${CMAKE_CURRENT_LIST_FILE} NAME) string(TIMESTAMP TIME_NOW "%Y-%m-%d %H:%M:%S") message(FATAL_ERROR "${TIME_NOW} - ${name}:${CMAKE_CURRENT_LIST_LINE} - ${msg}") endmacro(log_error) # debug(K1 K2 K3) # macro(debug) FOREACH(A ${ARGN}) log_debug("${A}:${${A}}") ENDFOREACH(A) endmacro(debug) ################### #no Special symbol in cmd macro(log_execute_process) set(options "" ) set(oneValueArgs WORKING_DIRECTORY ) set(multiValueArgs COMMAND) cmake_parse_arguments(log_execute_process "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) string(REPLACE ";" " " CMD "${log_execute_process_COMMAND}") if(NOT log_execute_process_WORKING_DIRECTORY) log_error("bad cmd:cd ${log_execute_process_WORKING_DIRECTORY} && ${CMD}") endif() if(NOT EXISTS ${log_execute_process_WORKING_DIRECTORY}) log_error("bad cmd:cd ${log_execute_process_WORKING_DIRECTORY} && ${CMD}") endif() log_debug("cd ${log_execute_process_WORKING_DIRECTORY} && ${CMD}") execute_process(COMMAND ${log_execute_process_COMMAND} WORKING_DIRECTORY ${log_execute_process_WORKING_DIRECTORY} RESULT_VARIABLE rv ERROR_VARIABLE er OUTPUT_FILE ${CMAKE_BINARY_DIR}/cmake_cmd_out.log ERROR_FILE ${CMAKE_BINARY_DIR}/cmake_error.log) if(rv) log_debug("RESULT:${rv}, CMD:${log_execute_process_COMMAND}") execute_process(COMMAND cat ${CMAKE_BINARY_DIR}/cmake_error.log WORKING_DIRECTORY ${log_execute_process_WORKING_DIRECTORY}) log_error("fatal error exit!") endif() endmacro(log_execute_process) macro(backup_and_mv_file) file(MAKE_DIRECTORY ${CMAKE_SOURCE_DIR}/.backup) FOREACH(C ${ARGN}) if(EXISTS ${C}) log_execute_process(COMMAND mv -f --backup=t ${C} -t ${CMAKE_SOURCE_DIR}/.backup WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) endif() ENDFOREACH(C) endmacro(backup_and_mv_file) macro(uncompress_package package output_dirname) get_filename_component(package_name ${package} NAME) get_filename_component(package_path ${package} PATH) if(${package_name} MATCHES ".zip$") string(FIND ${package_name} ".zip" LAST_POS REVERSE) set(UMCOMPRESS_CMD unzip -o) elseif(${package_name} MATCHES ".tar.gz$") string(FIND ${package_name} ".tar.gz" LAST_POS REVERSE) set(UMCOMPRESS_CMD tar zxvf) elseif(${package_name} MATCHES ".tar$") string(FIND ${package_name} ".tar" LAST_POS REVERSE) set(UMCOMPRESS_CMD tar xvf) endif() string(SUBSTRING ${package_name} 0 ${LAST_POS} dirname) set(package_dirname ${dirname} PARENT_SCOPE) if(NOT EXISTS ${output_dirname}) file(MAKE_DIRECTORY ${output_dirname}) endif() if(NOT EXISTS ${output_dirname}/${dirname}) log_execute_process(COMMAND ${UMCOMPRESS_CMD} ${package} WORKING_DIRECTORY ${output_dirname}) elseif(${package} IS_NEWER_THAN ${output_dirname}/${dirname}) #backup_and_mv_file(${output_dirname}/${dirname}) log_execute_process(COMMAND rm -fr ${output_dirname}/${dirname} WORKING_DIRECTORY ${output_dirname}) log_execute_process(COMMAND ${UMCOMPRESS_CMD} ${package} WORKING_DIRECTORY ${output_dirname}) endif() endmacro(uncompress_package) # # check_and_install(PACKAGE TARGET) # function(check_and_install) get_filename_component(install_dir_path ${CMAKE_CURRENT_LIST_FILE} PATH) get_filename_component(install_dir_name ${install_dir_path} NAME) set(options "" ) set(oneValueArgs "") set(multiValueArgs PACKAGE TARGET) cmake_parse_arguments(C "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) #0 parse args if(NOT C_PACKAGE OR NOT C_TARGET) log_error("check_and_install PACKAGE xx\n TARGET xx\n INSTALL xx\n CLEAR xx\n") endif() #debug(C_PACKAGE C_TARGET) # #1 check is package FOREACH(P ${C_PACKAGE}) if(NOT EXISTS ${P}) log_error("check_and_install: ${P} NOT FOUND") endif() ENDFOREACH(P) #1 check is need rebuild SET(${install_dir_name}_NEED_INSTALL FALSE) FOREACH(P ${C_PACKAGE}) FOREACH(T ${C_TARGET}) #1.1 target not exists if(NOT EXISTS ${T}) SET(${install_dir_name}_NEED_INSTALL TRUE) log_debug("check_and_install: ${T} NOT FOUND, INSTALL ${C_PACKAGE} to ${install_dir_path}, ${install_dir_name}_NEED_INSTALL:${${install_dir_name}_NEED_INSTALL}") break() endif() #1.2 target has been changed if(${P} IS_NEWER_THAN ${T}) log_debug("check_and_install: ${P} newer than ${T}, INSTALL ${C_PACKAGE} to ${install_dir_path}, ${install_dir_name}_NEED_INSTALL:${${install_dir_name}_NEED_INSTALL}") SET(${install_dir_name}_NEED_INSTALL TRUE) break() endif() ENDFOREACH(T) ENDFOREACH(P) #return SET(${install_dir_name}_NEED_INSTALL ${${install_dir_name}_NEED_INSTALL} PARENT_SCOPE) endfunction(check_and_install) function(find_and_set_package install_dir_path) set(options "" ) set(oneValueArgs INCLUDE LIB BIN) set(multiValueArgs "") cmake_parse_arguments(find_and_set_package "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if(NOT find_and_set_package_INCLUDE) SET(find_and_set_package_INCLUDE include) endif() if(NOT find_and_set_package_LIB) SET(find_and_set_package_LIB lib) endif() if(NOT find_and_set_package_BIN) SET(find_and_set_package_BIN bin) endif() get_filename_component(install_dir_name ${install_dir_path} NAME) set(PRE ${install_dir_name}) set(${PRE}_INSTALL_DIR ${install_dir_path}) SET(${PRE}_INCLUDE ${${PRE}_INSTALL_DIR}/${find_and_set_package_INCLUDE}) SET(${PRE}_LIB ${${PRE}_INSTALL_DIR}/${find_and_set_package_LIB}) SET(${PRE}_BIN ${${PRE}_INSTALL_DIR}/${find_and_set_package_BIN}) # include if(NOT EXISTS ${${PRE}_INCLUDE} ) log_error("${PRE}_INCLUDE:${${PRE}_INCLUDE} NOT FOUND, Please check_and_install first!") endif() file(GLOB_RECURSE ${PRE}_INCLUDES ${${PRE}_INCLUDE}/*.h) #if(NOT ${PRE}_INCLUDES) # log_warn("${${PRE}_INCLUDE} NOT FOUND HEADES, Please check_and_install first!") #endif() # use lib64 instead if(NOT EXISTS ${${PRE}_LIB}) SET(${PRE}_LIB ${${PRE}_INSTALL_DIR}/lib64) endif() # libs if(NOT EXISTS ${${PRE}_LIB} ) log_error("${${PRE}_LIB} NOT FOUND, Please check_and_install first!") endif() #static lib file(GLOB ${PRE}_STATIC_LIBS ${${PRE}_LIB}/lib*.a) FOREACH(A ${${PRE}_STATIC_LIBS}) get_filename_component(_lib_file_name ${A} NAME_WE) string(SUBSTRING ${_lib_file_name} 3 -1 _lib_name) if(NOT _lib_name) log_error("Bad lib name: ${A} in ${${PRE}_LIB}") endif() SET(${_lib_name}_A ${A} PARENT_SCOPE) add_library(${_lib_name}-static STATIC IMPORTED) set_property(TARGET ${_lib_name}-static PROPERTY IMPORTED_LOCATION ${A}) log_debug("SET ${_lib_name}-static: ${A}") ENDFOREACH(A) #sharelib file(GLOB ${PRE}_SHARED_LIBS ${${PRE}_LIB}/lib*.so) FOREACH(A ${${PRE}_SHARED_LIBS}) get_filename_component(_lib_file_name ${A} NAME_WE) string(SUBSTRING ${_lib_file_name} 3 -1 _lib_name) if(NOT _lib_name) log_error("Bad lib name: ${A} in ${${PRE}_LIB}") endif() SET(${_lib_name}_SO ${A}) add_library(${_lib_name}-shared SHARED IMPORTED) set_property(TARGET ${_lib_name}-shared PROPERTY IMPORTED_LOCATION ${A}) log_debug("SET ${_lib_name}-shared: ${A}") ENDFOREACH(A) # cmds file(GLOB ${PRE}_BINS ${${PRE}_BIN}/*) FOREACH(A ${${PRE}_BINS}) get_filename_component(P ${A} NAME) SET(${P}_BIN ${A}) log_debug("SET ${P}_BIN: ${${P}_BIN}") SET(${P}_BIN ${A} PARENT_SCOPE) ENDFOREACH(A) # FILES for ide #file(GLOB_RECURSE ${PRE}_FILES ${install_dir_path}/*) #source_group(${PRE}_IDE_VS FILES ${${PRE}_FILES}) #add_custom_target(${PRE}_IDE_QT SOURCES ${${PRE}_FILES}) #export to parent #set(PRE ${PRE} PARENT_SCOPE) #set(${PRE}_INSTALL_DIR ${${PRE}_INSTALL_DIR} PARENT_SCOPE) SET(${PRE}_INCLUDE ${${PRE}_INCLUDE} PARENT_SCOPE) SET(${PRE}_LIB ${${PRE}_LIB} PARENT_SCOPE) SET(${PRE}_BIN ${${PRE}_BIN} PARENT_SCOPE) #set(${PRE}_INCLUDES ${${PRE}_INCLUDES} PARENT_SCOPE) #set(${PRE}_STATIC_LIBS ${${PRE}_STATIC_LIBS} PARENT_SCOPE) #set(${PRE}_SHARED_LIBS ${${PRE}_SHARED_LIBS} PARENT_SCOPE) #set(${PRE}_BINS ${${PRE}_BINS} PARENT_SCOPE) #set(${PRE}_FILES ${${PRE}_FILES} PARENT_SCOPE) set(${PRE}_FOUND TRUE PARENT_SCOPE) endfunction(find_and_set_package) # include all subdirs function(recurse_include_directories DIR) file(GLOB_RECURSE _header_files FOLLOW_SYMLINKS ${DIR}/*.h) set(files_dirs "") foreach(src_file ${_header_files}) GET_FILENAME_COMPONENT(dir_path ${src_file} PATH) list(APPEND files_dirs ${dir_path}) endforeach() LIST(REMOVE_DUPLICATES files_dirs) include_directories(${DIR}) foreach(H ${files_dirs}) include_directories(${H}) endforeach(H) set(DIR_HEADERS ${_header_files} PARENT_SCOPE) endfunction(recurse_include_directories) function(add_source_to_qtcreator DIR) get_filename_component(dir_name ${DIR} NAME) string(REGEX REPLACE "/" "_" source_target ${DIR}) set(source_target "${dir_name}_${source_target}") log_debug("add_files_to_qtcreator: ${source_target}") # all header store in HEADERS_${DIR} #recurse_include_directories(${DIR}) # all c files .c / .cc / .cpp to c_src_files file(GLOB_RECURSE c_src_files FOLLOW_SYMLINKS ${DIR}/*[c|p|e]) set(other_files "") foreach(suffix ${ARGN}) file(GLOB_RECURSE other_src_files FOLLOW_SYMLINKS ${DIR}/*.${suffix}) list(APPEND other_files ${other_src_files}) endforeach() LIST(REMOVE_DUPLICATES other_files) add_custom_target(${source_target} SOURCES ${DIR_HEADERS} ${c_src_files} ${other_files} WORKING_DIRECTORY ${DIR}) set(DIR_ALLS ${DIR_HEADERS} ${c_src_files} ${other_files} PARENT_SCOPE) endfunction(add_source_to_qtcreator) macro(add_test_item) set(options "" ) set(oneValueArgs "") set(multiValueArgs SOURCES INCLUDES LIBS) cmake_parse_arguments(C "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) SET(TARGET "") FOREACH(P ${C_SOURCES}) get_filename_component(FILE_NAME ${P} NAME_WE) SET(TARGET "${FILE_NAME}") if(${TARGET} MATCHES "test_*") break() endif() ENDFOREACH(P) add_executable(${TARGET} ${C_SOURCES}) if(C_INCLUDES) target_include_directories(${TARGET} PUBLIC ${C_INCLUDES}) endif() if(C_LIBS) target_link_libraries(${TARGET} ${C_LIBS}) endif() add_test(NAME ${TARGET} COMMAND ${TARGET} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) log_debug("add_test:${TARGET}, srcs: ${C_SOURCES}") endmacro(add_test_item) # ngx_add_dynamic_module(DIR xxx SOURCES XXXX LIBS XXXX) macro(ngx_add_dynamic_module) set(options "" ) set(oneValueArgs "DIR") set(multiValueArgs SOURCES INCLUDES LIBS) cmake_parse_arguments(C "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if(NOT C_SOURCES) file(GLOB C_SRCS "${C_DIR}/*.c") file(GLOB C_HEADERS "${C_DIR}/*.h") file(GLOB CC_SRCS "${C_DIR}/*.cc") file(GLOB CPP_SRCS "${C_DIR}/*.cpp") file(GLOB HPP_SRCS "${C_DIR}/*.hpp") SET(C_SOURCES ${C_SRCS} ${C_HEADERS} ${CC_SRCS} ${CPP_SRCS} ${HPP_SRCS}) #debug(C_SOURCES C_SRCS CMAKE_CURRENT_SOURCE_DIR) endif() get_filename_component(module_name ${C_DIR} NAME) log_debug("add_dynamic_module:${module_name}, srcs: ${C_SOURCES}") add_library(${module_name} SHARED ${C_SOURCES}) if(C_INCLUDES) target_include_directories(${module_name} PUBLIC ${C_INCLUDES}) endif() if(C_LIBS) target_link_libraries(${module_name} PUBLIC ${C_LIBS}) endif() INSTALL(TARGETS ${C_DIR} DESTINATION shared) endmacro(ngx_add_dynamic_module) # ngx_add_static_module(DIR xxx SOURCES XXXX INCLUDES XXXLIBS XXXX) macro(ngx_add_static_module) set(options "" ) set(oneValueArgs "DIR") set(multiValueArgs SOURCES INCLUDES LIBS) cmake_parse_arguments(C "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if(NOT C_SOURCES) file(GLOB C_SRCS "${C_DIR}/*.c") file(GLOB C_HEADERS "${C_DIR}/*.h") file(GLOB CC_SRCS "${C_DIR}/*.cc") file(GLOB CPP_SRCS "${C_DIR}/*.cpp") file(GLOB HPP_SRCS "${C_DIR}/*.hpp") SET(C_SOURCES ${C_SRCS} ${C_HEADERS} ${CC_SRCS} ${CPP_SRCS} ${HPP_SRCS}) #debug(C_SOURCES C_SRCS CMAKE_CURRENT_SOURCE_DIR) endif() get_filename_component(module_name ${C_DIR} NAME) log_debug("add_static_module:${module_name}, srcs: ${C_SOURCES}") add_library(${module_name} STATIC ${C_SOURCES}) if(C_INCLUDES) target_include_directories(${module_name} PUBLIC ${C_INCLUDES}) endif() if(C_LIBS) # target is nginx static link target_link_libraries(nginx PUBLIC ${module_name} ${C_LIBS}) else() target_link_libraries(nginx PUBLIC ${module_name}) endif() #INSTALL(TARGETS ${C_DIR} DESTINATION shared) endmacro(ngx_add_static_module) function(grpc_gen_code SRCS HDRS) if(NOT ARGN) message(SEND_ERROR "Error: grpc_gen_code() called without any proto files") return() endif() set(PROTOBUF_GENERATE_CPP_APPEND_PATH TRUE) if(PROTOBUF_GENERATE_CPP_APPEND_PATH) # Create an include path for each file specified foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(ABS_PATH ${ABS_FIL} PATH) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if(${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif() endforeach() else() set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) endif() if(DEFINED PROTOBUF_IMPORT_DIRS) foreach(DIR ${PROTOBUF_IMPORT_DIRS}) get_filename_component(ABS_PATH ${DIR} ABSOLUTE) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if(${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif() endforeach() endif() set(${SRCS}) set(${HDRS}) foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(FIL_WE ${FIL} NAME_WE) list(APPEND ${SRCS} ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.grpc.pb.cc) list(APPEND ${HDRS} ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.grpc.pb.h) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.grpc.pb.cc ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.grpc.pb.h ${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_mock.grpc.pb.h COMMAND ${protoc_BIN} ARGS --grpc_out=generate_mock_code=true:${CMAKE_CURRENT_BINARY_DIR} --cpp_out=${CMAKE_CURRENT_BINARY_DIR} --plugin=protoc-gen-grpc=${grpc_cpp_plugin_BIN} ${_protobuf_include_path} ${ABS_FIL} DEPENDS ${ABS_FIL} ${PROTOBUF_PROTOC_EXECUTABLE} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Running gRPC C++ protocol buffer compiler on ${FIL}" VERBATIM) endforeach() set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE) set(${SRCS} ${${SRCS}} PARENT_SCOPE) set(${HDRS} ${${HDRS}} PARENT_SCOPE) endfunction() macro(add_shared_library DIR) SET(LIB_DIR ${DIR}/lib) if(NOT EXISTS ${LIB_DIR}) SET(LIB_DIR ${DIR}/lib64) endif() INCLUDE_DIRECTORIES(${DIR}/include) foreach(libname ${ARGN}) add_library(${libname} SHARED IMPORTED) set_property(TARGET ${libname} PROPERTY IMPORTED_LOCATION ${LIB_DIR}/lib${libname}.so) endforeach() log_debug("add_shared_library: ${ARGN} in: ${DIR}") endmacro(add_shared_library) macro(add_static_library DIR) set_property(GLOBAL APPEND PROPERTY GLOBAL_INCLUDE_DIRS "${DIR}/include") SET(LIB_DIR ${DIR}/lib) if(NOT EXISTS ${LIB_DIR}) SET(LIB_DIR ${DIR}/lib64) endif() set_property(GLOBAL APPEND PROPERTY GLOBAL_LINK_DIRS ${LIB_DIR}) INCLUDE_DIRECTORIES(${DIR}/include) #add_files_to_qtcreator(${DIR}/include .h .hpp) foreach(libname ${ARGN}) add_library(${libname} STATIC IMPORTED) set_property(TARGET ${libname} PROPERTY IMPORTED_LOCATION ${DIR}/lib/lib${libname}.a) endforeach() log_debug("add_static_library: ${ARGN} in: ${DIR}") endmacro(add_static_library) function(protoc_gen_code SRCS HDRS) if(NOT ARGN) message(SEND_ERROR "Error: protoc_gen_code() called without any proto files") return() endif() set(PROTOBUF_GENERATE_CPP_APPEND_PATH TRUE) if(PROTOBUF_GENERATE_CPP_APPEND_PATH) # Create an include path for each file specified foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(ABS_PATH ${ABS_FIL} PATH) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if(${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif() endforeach() else() set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) endif() if(DEFINED PROTOBUF_IMPORT_DIRS) foreach(DIR ${PROTOBUF_IMPORT_DIRS}) get_filename_component(ABS_PATH ${DIR} ABSOLUTE) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if(${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif() endforeach() endif() set(${SRCS}) set(${HDRS}) foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(FIL_WE ${FIL} NAME_WE) get_filename_component(FIL_PATH ${FIL} DIRECTORY) list(APPEND ${SRCS} ${FIL_PATH}/${FIL_WE}.pb.cc) list(APPEND ${HDRS} ${FIL_PATH}/${FIL_WE}.pb.h) #message("${${SRCS}} ${${HDRS}}") add_custom_command( OUTPUT ${FIL_PATH}/${FIL_WE}.pb.cc ${FIL_PATH}/${FIL_WE}.pb.h #${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_mock.grpc.pb.h COMMAND ${protoc_BIN} ARGS --cpp_out=${FIL_PATH} ${_protobuf_include_path} ${ABS_FIL} DEPENDS ${ABS_FIL} ${PROTOBUF_PROTOC_EXECUTABLE} WORKING_DIRECTORY ${FIL_PATH} COMMENT "Running C++ protocol buffer compiler on ${FIL}" VERBATIM) endforeach() set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE) set(${SRCS} ${${SRCS}} PARENT_SCOPE) set(${HDRS} ${${HDRS}} PARENT_SCOPE) endfunction() MACRO(SUBDIRLIST result curdir) FILE(GLOB children RELATIVE ${curdir} ${curdir}/[a-zA-Z0-9]*) SET(dirlist "") FOREACH(child ${children}) IF(IS_DIRECTORY ${curdir}/${child}) LIST(APPEND dirlist ${child}) ENDIF() ENDFOREACH() SET(${result} ${dirlist}) ENDMACRO() MACRO(IMPORT_ONE_LIB dep) # include every include SET(CURRENT_DIR ${dep}/include) if(IS_DIRECTORY ${CURRENT_DIR}) INCLUDE_DIRECTORIES(${CURRENT_DIR}) endif() set(mkl_regex ".*mkl.*") # #for bin file # FILE(GLOB children RELATIVE ${dep}/bin ${dep}/bin/*) # foreach(_bin_name ${children}) # if(TARGET ${_bin_name}) # get_property(_bin_dir TARGET ${_bin_name} PROPERTY IMPORTED_LOCATION) # log_warn("${_bin_name} already add at:${_bin_dir} skip ${dep}/bin/${_bin_name}") # continue() # endif() # add_executable(${_bin_name} IMPORTED) # set_property(TARGET ${_bin_name} PROPERTY IMPORTED_LOCATION ${dep}/bin/${_bin_name}) # log_debug("SET ${_bin_name}: ${dep}/bin/${_bin_name}") # endforeach() #for lib file foreach(CURRENT_DIR ${dep}/lib64 ${dep}/lib) FILE(GLOB children RELATIVE ${CURRENT_DIR} ${CURRENT_DIR}/lib*.a) foreach(libs ${children}) string(REGEX REPLACE "^lib" "" _lib_name ${libs}) string(REGEX REPLACE "\\.a" "" _lib_name ${_lib_name}) #set(_lib_name ${_lib_name}) if(TARGET ${_lib_name}) get_property(_lib_name_dir TARGET ${_lib_name} PROPERTY IMPORTED_LOCATION) log_warn("${_lib_name} already add at:${_lib_name_dir} skip ${CURRENT_DIR}/${libs}") continue() endif() add_library(${_lib_name} STATIC IMPORTED) set_property(TARGET ${_lib_name} PROPERTY IMPORTED_LOCATION ${CURRENT_DIR}/${libs}) log_debug("SET ${_lib_name}: ${CURRENT_DIR}/${libs}") endforeach() #for lib file FILE(GLOB children RELATIVE ${CURRENT_DIR} ${CURRENT_DIR}/lib*.so) foreach(libs ${children}) string(REGEX REPLACE "^lib" "" _lib_name ${libs}) string(REGEX REPLACE "\\.so" "" _lib_name ${_lib_name}) set(_lib_name ${_lib_name}-so) if(TARGET ${_lib_name}) get_property(_lib_name_dir TARGET ${_lib_name} PROPERTY IMPORTED_LOCATION) log_warn("${_lib_name} already add at:${_lib_name_dir} skip ${CURRENT_DIR}/${libs}") continue() endif() add_library(${_lib_name} SHARED IMPORTED) set_property(TARGET ${_lib_name} PROPERTY IMPORTED_LOCATION ${CURRENT_DIR}/${libs}) log_debug("SET ${_lib_name}: ${CURRENT_DIR}/${libs}") if ("${_lib_name}" MATCHES "${mkl_regex}") log_debug("${_lib_name}: IMPORTED_NO_SONAME") set_property(TARGET ${_lib_name} PROPERTY IMPORTED_NO_SONAME 1) endif() endforeach() endforeach() ENDMACRO() MACRO(ADD_THIRD_LIB THIRD_PATH) SUBDIRLIST(SUB_THIRD_DIRS ${THIRD_PATH}) message(STATUS "SUB_THIRD_LIBS: ${SUB_THIRD_DIRS}") set(cuda8_regex ".*cuda8.*") set(cuda9_regex ".*cuda9.*") set(cuda10_regex ".*cuda10.*") foreach(dep ${SUB_THIRD_DIRS}) message(STATUS "dep: ${dep}") if("${dep}" MATCHES "${cuda8_regex}") if(${CUDA8_0}) message(STATUS "add ${THIRD_PATH}/${deps}") IMPORT_ONE_LIB(${THIRD_PATH}/${dep}) set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -Xcompiler -fPIC -O3 --compiler-options -fno-strict-aliasing -lineinfo -Xptxas -dlcm=cg -use_fast_math -gencode arch=compute_61,code=sm_61 -gencode arch=compute_60,code=sm_60 -gencode arch=compute_52,code=sm_52" CACHE STRING "cuda flags") message(STATUS "CUDA_NVCC_FLAGS:${CUDA_NVCC_FLAGS}") endif(${CUDA8_0}) elseif("${dep}" MATCHES "${cuda9_regex}") if(${CUDA9_0}) message(STATUS "add ${THIRD_PATH}/${deps}") IMPORT_ONE_LIB(${THIRD_PATH}/${dep}) set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -Xcompiler -fPIC -O3 --compiler-options -fno-strict-aliasing -lineinfo -Xptxas -dlcm=cg -use_fast_math -gencode arch=compute_70,code=sm_70 -gencode arch=compute_61,code=sm_61 -gencode arch=compute_60,code=sm_60 -gencode arch=compute_52,code=sm_52" CACHE STRING "cuda flags") message(STATUS "CUDA_NVCC_FLAGS:${CUDA_NVCC_FLAGS}") endif(${CUDA9_0}) elseif("${dep}" MATCHES "${cuda10_regex}") if(${CUDA10_0}) message(STATUS "add ${THIRD_PATH}/${deps}") IMPORT_ONE_LIB(${THIRD_PATH}/${dep}) set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -Xcompiler -fPIC -O3 --compiler-options -fno-strict-aliasing -lineinfo -Xptxas -dlcm=cg -use_fast_math -gencode arch=compute_75,code=sm_75 -gencode arch=compute_70,code=sm_70 -gencode arch=compute_61,code=sm_61 -gencode arch=compute_60,code=sm_60 -gencode arch=compute_52,code=sm_52" CACHE STRING "cuda flags") message(STATUS "CUDA_NVCC_FLAGS:${CUDA_NVCC_FLAGS}") endif(${CUDA10_0}) else("${dep}" MATCHES "${cuda8_regex}") message(STATUS "not cuda8 or cuda9 lib. normal import") IMPORT_ONE_LIB(${THIRD_PATH}/${dep}) endif("${dep}" MATCHES "${cuda8_regex}") endforeach() ENDMACRO() MACRO(INSTALL_SO LIB_DIR) # todo copy by bin foreach(so_target ${ARGN}) get_property(SO_FILE TARGET ${so_target} PROPERTY IMPORTED_LOCATION) if(SO_FILE MATCHES ".so$") log_debug("INSTALL LIBRARY ${SO_FILE}") file(GLOB ALL_SOS "${SO_FILE}*") INSTALL(FILES ${ALL_SOS} DESTINATION ${LIB_DIR}) endif() endforeach() ENDMACRO() MACRO(INSTALL_BIN BIN_DIR) foreach(bin_target ${ARGN}) get_property(BIN_FILE TARGET ${bin_target} PROPERTY IMPORTED_LOCATION) log_debug("INSTALL BINARY ${BIN_FILE}") INSTALL(FILES ${BIN_FILE} DESTINATION ${BIN_DIR}) endforeach() ENDMACRO() #build type #flag to import CUDA8.0/9.0/10.0 option(BUILD_CUDA8_0 "BUILD_CUDA8_0" OFF) set(CUDA8_0 FALSE) if(BUILD_CUDA8_0) set(CUDA8_0 TRUE) endif(BUILD_CUDA8_0) option(BUILD_CUDA9_0 "BUILD_CUDA9_0" OFF) set(CUDA9_0 FALSE) if(BUILD_CUDA9_0) set(CUDA9_0 TRUE) endif(BUILD_CUDA9_0) option(BUILD_CUDA10_0 "BUILD_CUDA10_0" OFF) set(CUDA10_0 FALSE) if(BUILD_CUDA10_0) set(CUDA10_0 TRUE) endif(BUILD_CUDA10_0) set(THIRD_PATH ${CMAKE_SOURCE_DIR}/third_path) if(NOT EXISTS ${THIRD_PATH}) set(THIRD_PATH ${CMAKE_SOURCE_DIR}/../third_path) endif() message(STATUS "THIRD_PATH;${THIRD_PATH}") ADD_THIRD_LIB(${THIRD_PATH}) IF(CUDA8_0) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda8_0) include(FindCUDA) message(STATUS "FindCUDA - CUDA_TOOLKIT_ROOT_DIR: ${THIRD_PATH}/cuda8_0; ") ELSE(CUDA8_0) IF(IS_DIRECTORY ${THIRD_PATH}/cuda) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda) include(FindCUDA) ELSE(IS_DIRECTORY ${THIRD_PATH}/cuda) ENDIF() ENDIF() IF(CUDA9_0) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda9_0) include(FindCUDA) message(STATUS "FindCUDA - CUDA_TOOLKIT_ROOT_DIR: ${THIRD_PATH}/cuda9_0; ") ELSE(CUDA9_0) IF(IS_DIRECTORY ${THIRD_PATH}/cuda) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda) include(FindCUDA) ELSE(IS_DIRECTORY ${THIRD_PATH}/cuda) ENDIF() ENDIF() IF(CUDA10_0) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda10_0) include(FindCUDA) message(STATUS "FindCUDA - CUDA_TOOLKIT_ROOT_DIR: ${THIRD_PATH}/cuda10_0; ") ELSE(CUDA10_0) IF(IS_DIRECTORY ${THIRD_PATH}/cuda) set(CUDA_TOOLKIT_ROOT_DIR ${THIRD_PATH}/cuda) include(FindCUDA) ELSE(IS_DIRECTORY ${THIRD_PATH}/cuda) ENDIF() ENDIF() ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/types/CMakeLists.txt ================================================ find_package(Protobuf REQUIRED) list(APPEND IMPORT_DIRS "${PROJECT_SOURCE_DIR}") GENERATE_PROTOBUF_LIB("${IMPORT_DIRS}" "") ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/types/code/code.error.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 code import ( "fmt" "strings" ) func (x *CgoError) Error() string { var msg strings.Builder msg.WriteString(fmt.Sprintf("cgo (%d)", x.GetErrorCode())) if x.GetErrorMessage() != "" { msg.WriteString(fmt.Sprintf(", %s", x.GetErrorMessage())) } if x.GetSdkErrorCode() != 0 { msg.WriteString(fmt.Sprintf(": sdk(%d)", x.GetSdkErrorCode())) if x.GetSdkErrorMessage() != "" { msg.WriteString(fmt.Sprintf(", %s", x.GetSdkErrorMessage())) } } return msg.String() } ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/types/code/sdk-go.code.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.17.3 // source: types/code/sdk-go.code.proto package code import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Code int32 const ( // OK is returned on success. Code_OK Code = 0 // Canceled indicates the operation was canceled (typically by the // caller). // // The gRPC framework will generate this error code when cancellation // is requested. Code_Canceled Code = 1 // Unknown error. An example of where this error may be returned is // if a Status value received from another address space belongs to // an error-space that is not known in this address space. Also // errors raised by APIs that do not return enough error information // may be converted to this error. // // The gRPC framework will generate this error code in the above two // mentioned cases. Code_Unknown Code = 2 // InvalidArgument indicates client specified an invalid argument. // Note that this differs from FailedPrecondition. It indicates arguments // that are problematic regardless of the state of the system // (e.g., a malformed file name). // // This error code will not be generated by the gRPC framework. Code_InvalidArgument Code = 3 // DeadlineExceeded means operation expired before completion. // For operations that change the state of the system, this error may be // returned even if the operation has completed successfully. For // example, a successful response from a server could have been delayed // long enough for the deadline to expire. // // The gRPC framework will generate this error code when the deadline is // exceeded. Code_DeadlineExceeded Code = 4 // NotFound means some requested entity (e.g., file or directory) was // not found. // // This error code will not be generated by the gRPC framework. Code_NotFound Code = 5 // AlreadyExists means an attempt to create an entity failed because one // already exists. // // This error code will not be generated by the gRPC framework. Code_AlreadyExists Code = 6 // PermissionDenied indicates the caller does not have permission to // execute the specified operation. It must not be used for rejections // caused by exhausting some resource (use ResourceExhausted // instead for those errors). It must not be // used if the caller cannot be identified (use Unauthenticated // instead for those errors). // // This error code will not be generated by the gRPC core framework, // but expect authentication middleware to use it. Code_PermissionDenied Code = 7 // ResourceExhausted indicates some resource has been exhausted, perhaps // a per-user quota, or perhaps the entire file system is out of space. // // This error code will be generated by the gRPC framework in // out-of-memory and server overload situations, or when a message is // larger than the configured maximum size. Code_ResourceExhausted Code = 8 // FailedPrecondition indicates operation was rejected because the // system is not in a state required for the operation's execution. // For example, directory to be deleted may be non-empty, an rmdir // operation is applied to a non-directory, etc. // // A litmus test that may help a service implementor in deciding // between FailedPrecondition, Aborted, and Unavailable: // (a) Use Unavailable if the client can retry just the failing call. // (b) Use Aborted if the client should retry at a higher-level // (e.g., restarting a read-modify-write sequence). // (c) Use FailedPrecondition if the client should not retry until // the system state has been explicitly fixed. E.g., if an "rmdir" // fails because the directory is non-empty, FailedPrecondition // should be returned since the client should not retry unless // they have first fixed up the directory by deleting files from it. // (d) Use FailedPrecondition if the client performs conditional // REST Get/Update/Delete on a resource and the resource on the // server does not match the condition. E.g., conflicting // read-modify-write on the same resource. // // This error code will not be generated by the gRPC framework. Code_FailedPrecondition Code = 9 // Aborted indicates the operation was aborted, typically due to a // concurrency issue like sequencer check failures, transaction aborts, // etc. // // See litmus test above for deciding between FailedPrecondition, // Aborted, and Unavailable. // // This error code will not be generated by the gRPC framework. Code_Aborted Code = 10 // OutOfRange means operation was attempted past the valid range. // E.g., seeking or reading past end of file. // // Unlike InvalidArgument, this error indicates a problem that may // be fixed if the system state changes. For example, a 32-bit file // system will generate InvalidArgument if asked to read at an // offset that is not in the range [0,2^32-1], but it will generate // OutOfRange if asked to read from an offset past the current // file size. // // There is a fair bit of overlap between FailedPrecondition and // OutOfRange. We recommend using OutOfRange (the more specific // error) when it applies so that callers who are iterating through // a space can easily look for an OutOfRange error to detect when // they are done. // // This error code will not be generated by the gRPC framework. Code_OutOfRange Code = 11 // Unimplemented indicates operation is not implemented or not // supported/enabled in this service. // // This error code will be generated by the gRPC framework. Most // commonly, you will see this error code when a method implementation // is missing on the server. It can also be generated for unknown // compression algorithms or a disagreement as to whether an RPC should // be streaming. Code_Unimplemented Code = 12 // Internal errors. Means some invariants expected by underlying // system has been broken. If you see one of these errors, // something is very broken. // // This error code will be generated by the gRPC framework in several // internal error conditions. Code_Internal Code = 13 // Unavailable indicates the service is currently unavailable. // This is a most likely a transient condition and may be corrected // by retrying with a backoff. Note that it is not always safe to retry // non-idempotent operations. // // See litmus test above for deciding between FailedPrecondition, // Aborted, and Unavailable. // // This error code will be generated by the gRPC framework during // abrupt shutdown of a server process or network connection. Code_Unavailable Code = 14 // DataLoss indicates unrecoverable data loss or corruption. // // This error code will not be generated by the gRPC framework. Code_DataLoss Code = 15 // Unauthenticated indicates the request does not have valid // authentication credentials for the operation. // // The gRPC framework will generate this error code when the // authentication metadata is invalid or a Credentials callback fails, // but also expect authentication middleware to generate it. Code_Unauthenticated Code = 16 ) // Enum value maps for Code. var ( Code_name = map[int32]string{ 0: "OK", 1: "Canceled", 2: "Unknown", 3: "InvalidArgument", 4: "DeadlineExceeded", 5: "NotFound", 6: "AlreadyExists", 7: "PermissionDenied", 8: "ResourceExhausted", 9: "FailedPrecondition", 10: "Aborted", 11: "OutOfRange", 12: "Unimplemented", 13: "Internal", 14: "Unavailable", 15: "DataLoss", 16: "Unauthenticated", } Code_value = map[string]int32{ "OK": 0, "Canceled": 1, "Unknown": 2, "InvalidArgument": 3, "DeadlineExceeded": 4, "NotFound": 5, "AlreadyExists": 6, "PermissionDenied": 7, "ResourceExhausted": 8, "FailedPrecondition": 9, "Aborted": 10, "OutOfRange": 11, "Unimplemented": 12, "Internal": 13, "Unavailable": 14, "DataLoss": 15, "Unauthenticated": 16, } ) func (x Code) Enum() *Code { p := new(Code) *p = x return p } func (x Code) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Code) Descriptor() protoreflect.EnumDescriptor { return file_types_code_sdk_go_code_proto_enumTypes[0].Descriptor() } func (Code) Type() protoreflect.EnumType { return &file_types_code_sdk_go_code_proto_enumTypes[0] } func (x Code) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Code.Descriptor instead. func (Code) EnumDescriptor() ([]byte, []int) { return file_types_code_sdk_go_code_proto_rawDescGZIP(), []int{0} } type CgoError struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ErrorCode Code `protobuf:"varint,1,opt,name=error_code,json=errorCode,proto3,enum=sdk.types.code.Code" json:"error_code,omitempty"` ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` SdkErrorCode int32 `protobuf:"varint,3,opt,name=sdk_error_code,json=sdkErrorCode,proto3" json:"sdk_error_code,omitempty"` SdkErrorMessage string `protobuf:"bytes,4,opt,name=sdk_error_message,json=sdkErrorMessage,proto3" json:"sdk_error_message,omitempty"` } func (x *CgoError) Reset() { *x = CgoError{} if protoimpl.UnsafeEnabled { mi := &file_types_code_sdk_go_code_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CgoError) String() string { return protoimpl.X.MessageStringOf(x) } func (*CgoError) ProtoMessage() {} func (x *CgoError) ProtoReflect() protoreflect.Message { mi := &file_types_code_sdk_go_code_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CgoError.ProtoReflect.Descriptor instead. func (*CgoError) Descriptor() ([]byte, []int) { return file_types_code_sdk_go_code_proto_rawDescGZIP(), []int{0} } func (x *CgoError) GetErrorCode() Code { if x != nil { return x.ErrorCode } return Code_OK } func (x *CgoError) GetErrorMessage() string { if x != nil { return x.ErrorMessage } return "" } func (x *CgoError) GetSdkErrorCode() int32 { if x != nil { return x.SdkErrorCode } return 0 } func (x *CgoError) GetSdkErrorMessage() string { if x != nil { return x.SdkErrorMessage } return "" } var File_types_code_sdk_go_code_proto protoreflect.FileDescriptor var file_types_code_sdk_go_code_proto_rawDesc = []byte{ 0x0a, 0x1c, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x2f, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0e, 0x73, 0x64, 0x6b, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x22, 0xb6, 0x01, 0x0a, 0x08, 0x43, 0x67, 0x6f, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x33, 0x0a, 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x14, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x24, 0x0a, 0x0e, 0x73, 0x64, 0x6b, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, 0x73, 0x64, 0x6b, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x2a, 0x0a, 0x11, 0x73, 0x64, 0x6b, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x73, 0x64, 0x6b, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2a, 0xac, 0x02, 0x0a, 0x04, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x65, 0x64, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x10, 0x02, 0x12, 0x13, 0x0a, 0x0f, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x41, 0x72, 0x67, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x10, 0x03, 0x12, 0x14, 0x0a, 0x10, 0x44, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x45, 0x78, 0x63, 0x65, 0x65, 0x64, 0x65, 0x64, 0x10, 0x04, 0x12, 0x0c, 0x0a, 0x08, 0x4e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x10, 0x05, 0x12, 0x11, 0x0a, 0x0d, 0x41, 0x6c, 0x72, 0x65, 0x61, 0x64, 0x79, 0x45, 0x78, 0x69, 0x73, 0x74, 0x73, 0x10, 0x06, 0x12, 0x14, 0x0a, 0x10, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x65, 0x6e, 0x69, 0x65, 0x64, 0x10, 0x07, 0x12, 0x15, 0x0a, 0x11, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x45, 0x78, 0x68, 0x61, 0x75, 0x73, 0x74, 0x65, 0x64, 0x10, 0x08, 0x12, 0x16, 0x0a, 0x12, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x50, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x09, 0x12, 0x0b, 0x0a, 0x07, 0x41, 0x62, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x10, 0x0a, 0x12, 0x0e, 0x0a, 0x0a, 0x4f, 0x75, 0x74, 0x4f, 0x66, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x10, 0x0b, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x6e, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x64, 0x10, 0x0c, 0x12, 0x0c, 0x0a, 0x08, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x10, 0x0d, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x10, 0x0e, 0x12, 0x0c, 0x0a, 0x08, 0x44, 0x61, 0x74, 0x61, 0x4c, 0x6f, 0x73, 0x73, 0x10, 0x0f, 0x12, 0x13, 0x0a, 0x0f, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x64, 0x10, 0x10, 0x42, 0x48, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x67, 0x6f, 0x63, 0x76, 0x2f, 0x63, 0x67, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2d, 0x73, 0x70, 0x65, 0x63, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x3b, 0x63, 0x6f, 0x64, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_types_code_sdk_go_code_proto_rawDescOnce sync.Once file_types_code_sdk_go_code_proto_rawDescData = file_types_code_sdk_go_code_proto_rawDesc ) func file_types_code_sdk_go_code_proto_rawDescGZIP() []byte { file_types_code_sdk_go_code_proto_rawDescOnce.Do(func() { file_types_code_sdk_go_code_proto_rawDescData = protoimpl.X.CompressGZIP(file_types_code_sdk_go_code_proto_rawDescData) }) return file_types_code_sdk_go_code_proto_rawDescData } var file_types_code_sdk_go_code_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_types_code_sdk_go_code_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_types_code_sdk_go_code_proto_goTypes = []interface{}{ (Code)(0), // 0: sdk.types.code.Code (*CgoError)(nil), // 1: sdk.types.code.CgoError } var file_types_code_sdk_go_code_proto_depIdxs = []int32{ 0, // 0: sdk.types.code.CgoError.error_code:type_name -> sdk.types.code.Code 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_types_code_sdk_go_code_proto_init() } func file_types_code_sdk_go_code_proto_init() { if File_types_code_sdk_go_code_proto != nil { return } if !protoimpl.UnsafeEnabled { file_types_code_sdk_go_code_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CgoError); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_types_code_sdk_go_code_proto_rawDesc, NumEnums: 1, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_types_code_sdk_go_code_proto_goTypes, DependencyIndexes: file_types_code_sdk_go_code_proto_depIdxs, EnumInfos: file_types_code_sdk_go_code_proto_enumTypes, MessageInfos: file_types_code_sdk_go_code_proto_msgTypes, }.Build() File_types_code_sdk_go_code_proto = out.File file_types_code_sdk_go_code_proto_rawDesc = nil file_types_code_sdk_go_code_proto_goTypes = nil file_types_code_sdk_go_code_proto_depIdxs = nil } ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/types/code/sdk-go.code.pb.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: api/openapi-spec/types/code/sdk-go.code.proto #ifndef PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2ftypes_2fcode_2fsdk_2dgo_2ecode_2eproto #define PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2ftypes_2fcode_2fsdk_2dgo_2ecode_2eproto #include #include #if GOOGLE_PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include #include #include #include #include #include #include #include #include // IWYU pragma: export #include // IWYU pragma: export #include #include // @@protoc_insertion_point(includes) #define PROTOBUF_INTERNAL_EXPORT_protobuf_api_2fopenapi_2dspec_2ftypes_2fcode_2fsdk_2dgo_2ecode_2eproto namespace protobuf_api_2fopenapi_2dspec_2ftypes_2fcode_2fsdk_2dgo_2ecode_2eproto { // Internal implementation detail -- do not use these members. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[1]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; void AddDescriptors(); } // namespace protobuf_api_2fopenapi_2dspec_2ftypes_2fcode_2fsdk_2dgo_2ecode_2eproto namespace sdk { namespace types { namespace code { class CgoError; class CgoErrorDefaultTypeInternal; extern CgoErrorDefaultTypeInternal _CgoError_default_instance_; } // namespace code } // namespace types } // namespace sdk namespace google { namespace protobuf { template<> ::sdk::types::code::CgoError* Arena::CreateMaybeMessage<::sdk::types::code::CgoError>(Arena*); } // namespace protobuf } // namespace google namespace sdk { namespace types { namespace code { enum Code { OK = 0, Canceled = 1, Unknown = 2, InvalidArgument = 3, DeadlineExceeded = 4, NotFound = 5, AlreadyExists = 6, PermissionDenied = 7, ResourceExhausted = 8, FailedPrecondition = 9, Aborted = 10, OutOfRange = 11, Unimplemented = 12, Internal = 13, Unavailable = 14, DataLoss = 15, Unauthenticated = 16, Code_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, Code_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max }; bool Code_IsValid(int value); const Code Code_MIN = OK; const Code Code_MAX = Unauthenticated; const int Code_ARRAYSIZE = Code_MAX + 1; const ::google::protobuf::EnumDescriptor* Code_descriptor(); inline const ::std::string& Code_Name(Code value) { return ::google::protobuf::internal::NameOfEnum( Code_descriptor(), value); } inline bool Code_Parse( const ::std::string& name, Code* value) { return ::google::protobuf::internal::ParseNamedEnum( Code_descriptor(), name, value); } // =================================================================== class CgoError : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:sdk.types.code.CgoError) */ { public: CgoError(); virtual ~CgoError(); CgoError(const CgoError& from); inline CgoError& operator=(const CgoError& from) { CopyFrom(from); return *this; } #if LANG_CXX11 CgoError(CgoError&& from) noexcept : CgoError() { *this = ::std::move(from); } inline CgoError& operator=(CgoError&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const CgoError& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const CgoError* internal_default_instance() { return reinterpret_cast( &_CgoError_default_instance_); } static constexpr int kIndexInFileMessages = 0; void Swap(CgoError* other); friend void swap(CgoError& a, CgoError& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline CgoError* New() const final { return CreateMaybeMessage(NULL); } CgoError* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const CgoError& from); void MergeFrom(const CgoError& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CgoError* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string error_message = 2; void clear_error_message(); static const int kErrorMessageFieldNumber = 2; const ::std::string& error_message() const; void set_error_message(const ::std::string& value); #if LANG_CXX11 void set_error_message(::std::string&& value); #endif void set_error_message(const char* value); void set_error_message(const char* value, size_t size); ::std::string* mutable_error_message(); ::std::string* release_error_message(); void set_allocated_error_message(::std::string* error_message); // string sdk_error_message = 4; void clear_sdk_error_message(); static const int kSdkErrorMessageFieldNumber = 4; const ::std::string& sdk_error_message() const; void set_sdk_error_message(const ::std::string& value); #if LANG_CXX11 void set_sdk_error_message(::std::string&& value); #endif void set_sdk_error_message(const char* value); void set_sdk_error_message(const char* value, size_t size); ::std::string* mutable_sdk_error_message(); ::std::string* release_sdk_error_message(); void set_allocated_sdk_error_message(::std::string* sdk_error_message); // .sdk.types.code.Code error_code = 1; void clear_error_code(); static const int kErrorCodeFieldNumber = 1; ::sdk::types::code::Code error_code() const; void set_error_code(::sdk::types::code::Code value); // int32 sdk_error_code = 3; void clear_sdk_error_code(); static const int kSdkErrorCodeFieldNumber = 3; ::google::protobuf::int32 sdk_error_code() const; void set_sdk_error_code(::google::protobuf::int32 value); // @@protoc_insertion_point(class_scope:sdk.types.code.CgoError) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr error_message_; ::google::protobuf::internal::ArenaStringPtr sdk_error_message_; int error_code_; ::google::protobuf::int32 sdk_error_code_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_api_2fopenapi_2dspec_2ftypes_2fcode_2fsdk_2dgo_2ecode_2eproto::TableStruct; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // CgoError // .sdk.types.code.Code error_code = 1; inline void CgoError::clear_error_code() { error_code_ = 0; } inline ::sdk::types::code::Code CgoError::error_code() const { // @@protoc_insertion_point(field_get:sdk.types.code.CgoError.error_code) return static_cast< ::sdk::types::code::Code >(error_code_); } inline void CgoError::set_error_code(::sdk::types::code::Code value) { error_code_ = value; // @@protoc_insertion_point(field_set:sdk.types.code.CgoError.error_code) } // string error_message = 2; inline void CgoError::clear_error_message() { error_message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& CgoError::error_message() const { // @@protoc_insertion_point(field_get:sdk.types.code.CgoError.error_message) return error_message_.GetNoArena(); } inline void CgoError::set_error_message(const ::std::string& value) { error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sdk.types.code.CgoError.error_message) } #if LANG_CXX11 inline void CgoError::set_error_message(::std::string&& value) { error_message_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sdk.types.code.CgoError.error_message) } #endif inline void CgoError::set_error_message(const char* value) { GOOGLE_DCHECK(value != NULL); error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sdk.types.code.CgoError.error_message) } inline void CgoError::set_error_message(const char* value, size_t size) { error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:sdk.types.code.CgoError.error_message) } inline ::std::string* CgoError::mutable_error_message() { // @@protoc_insertion_point(field_mutable:sdk.types.code.CgoError.error_message) return error_message_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* CgoError::release_error_message() { // @@protoc_insertion_point(field_release:sdk.types.code.CgoError.error_message) return error_message_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CgoError::set_allocated_error_message(::std::string* error_message) { if (error_message != NULL) { } else { } error_message_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), error_message); // @@protoc_insertion_point(field_set_allocated:sdk.types.code.CgoError.error_message) } // int32 sdk_error_code = 3; inline void CgoError::clear_sdk_error_code() { sdk_error_code_ = 0; } inline ::google::protobuf::int32 CgoError::sdk_error_code() const { // @@protoc_insertion_point(field_get:sdk.types.code.CgoError.sdk_error_code) return sdk_error_code_; } inline void CgoError::set_sdk_error_code(::google::protobuf::int32 value) { sdk_error_code_ = value; // @@protoc_insertion_point(field_set:sdk.types.code.CgoError.sdk_error_code) } // string sdk_error_message = 4; inline void CgoError::clear_sdk_error_message() { sdk_error_message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& CgoError::sdk_error_message() const { // @@protoc_insertion_point(field_get:sdk.types.code.CgoError.sdk_error_message) return sdk_error_message_.GetNoArena(); } inline void CgoError::set_sdk_error_message(const ::std::string& value) { sdk_error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sdk.types.code.CgoError.sdk_error_message) } #if LANG_CXX11 inline void CgoError::set_sdk_error_message(::std::string&& value) { sdk_error_message_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sdk.types.code.CgoError.sdk_error_message) } #endif inline void CgoError::set_sdk_error_message(const char* value) { GOOGLE_DCHECK(value != NULL); sdk_error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sdk.types.code.CgoError.sdk_error_message) } inline void CgoError::set_sdk_error_message(const char* value, size_t size) { sdk_error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast(value), size)); // @@protoc_insertion_point(field_set_pointer:sdk.types.code.CgoError.sdk_error_message) } inline ::std::string* CgoError::mutable_sdk_error_message() { // @@protoc_insertion_point(field_mutable:sdk.types.code.CgoError.sdk_error_message) return sdk_error_message_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* CgoError::release_sdk_error_message() { // @@protoc_insertion_point(field_release:sdk.types.code.CgoError.sdk_error_message) return sdk_error_message_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CgoError::set_allocated_sdk_error_message(::std::string* sdk_error_message) { if (sdk_error_message != NULL) { } else { } sdk_error_message_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), sdk_error_message); // @@protoc_insertion_point(field_set_allocated:sdk.types.code.CgoError.sdk_error_message) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace code } // namespace types } // namespace sdk namespace google { namespace protobuf { template <> struct is_proto_enum< ::sdk::types::code::Code> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::sdk::types::code::Code>() { return ::sdk::types::code::Code_descriptor(); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2ftypes_2fcode_2fsdk_2dgo_2ecode_2eproto ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/types/code/sdk-go.code.proto ================================================ syntax = "proto3"; package sdk.types.code; option go_package = "github.com/kaydxh/golang/pkg/gocv/cgo/api/openapi-spec/types/code;code"; message CgoError { Code error_code = 1; string error_message = 2; int32 sdk_error_code = 3; string sdk_error_message = 4; } enum Code { // OK is returned on success. OK = 0; // Canceled indicates the operation was canceled (typically by the // caller). // // The gRPC framework will generate this error code when cancellation // is requested. Canceled = 1; // Unknown error. An example of where this error may be returned is // if a Status value received from another address space belongs to // an error-space that is not known in this address space. Also // errors raised by APIs that do not return enough error information // may be converted to this error. // // The gRPC framework will generate this error code in the above two // mentioned cases. Unknown = 2; // InvalidArgument indicates client specified an invalid argument. // Note that this differs from FailedPrecondition. It indicates arguments // that are problematic regardless of the state of the system // (e.g., a malformed file name). // // This error code will not be generated by the gRPC framework. InvalidArgument = 3; // DeadlineExceeded means operation expired before completion. // For operations that change the state of the system, this error may be // returned even if the operation has completed successfully. For // example, a successful response from a server could have been delayed // long enough for the deadline to expire. // // The gRPC framework will generate this error code when the deadline is // exceeded. DeadlineExceeded = 4; // NotFound means some requested entity (e.g., file or directory) was // not found. // // This error code will not be generated by the gRPC framework. NotFound = 5; // AlreadyExists means an attempt to create an entity failed because one // already exists. // // This error code will not be generated by the gRPC framework. AlreadyExists = 6; // PermissionDenied indicates the caller does not have permission to // execute the specified operation. It must not be used for rejections // caused by exhausting some resource (use ResourceExhausted // instead for those errors). It must not be // used if the caller cannot be identified (use Unauthenticated // instead for those errors). // // This error code will not be generated by the gRPC core framework, // but expect authentication middleware to use it. PermissionDenied = 7; // ResourceExhausted indicates some resource has been exhausted, perhaps // a per-user quota, or perhaps the entire file system is out of space. // // This error code will be generated by the gRPC framework in // out-of-memory and server overload situations, or when a message is // larger than the configured maximum size. ResourceExhausted = 8; // FailedPrecondition indicates operation was rejected because the // system is not in a state required for the operation's execution. // For example, directory to be deleted may be non-empty, an rmdir // operation is applied to a non-directory, etc. // // A litmus test that may help a service implementor in deciding // between FailedPrecondition, Aborted, and Unavailable: // (a) Use Unavailable if the client can retry just the failing call. // (b) Use Aborted if the client should retry at a higher-level // (e.g., restarting a read-modify-write sequence). // (c) Use FailedPrecondition if the client should not retry until // the system state has been explicitly fixed. E.g., if an "rmdir" // fails because the directory is non-empty, FailedPrecondition // should be returned since the client should not retry unless // they have first fixed up the directory by deleting files from it. // (d) Use FailedPrecondition if the client performs conditional // REST Get/Update/Delete on a resource and the resource on the // server does not match the condition. E.g., conflicting // read-modify-write on the same resource. // // This error code will not be generated by the gRPC framework. FailedPrecondition = 9; // Aborted indicates the operation was aborted, typically due to a // concurrency issue like sequencer check failures, transaction aborts, // etc. // // See litmus test above for deciding between FailedPrecondition, // Aborted, and Unavailable. // // This error code will not be generated by the gRPC framework. Aborted = 10; // OutOfRange means operation was attempted past the valid range. // E.g., seeking or reading past end of file. // // Unlike InvalidArgument, this error indicates a problem that may // be fixed if the system state changes. For example, a 32-bit file // system will generate InvalidArgument if asked to read at an // offset that is not in the range [0,2^32-1], but it will generate // OutOfRange if asked to read from an offset past the current // file size. // // There is a fair bit of overlap between FailedPrecondition and // OutOfRange. We recommend using OutOfRange (the more specific // error) when it applies so that callers who are iterating through // a space can easily look for an OutOfRange error to detect when // they are done. // // This error code will not be generated by the gRPC framework. OutOfRange = 11; // Unimplemented indicates operation is not implemented or not // supported/enabled in this service. // // This error code will be generated by the gRPC framework. Most // commonly, you will see this error code when a method implementation // is missing on the server. It can also be generated for unknown // compression algorithms or a disagreement as to whether an RPC should // be streaming. Unimplemented = 12; // Internal errors. Means some invariants expected by underlying // system has been broken. If you see one of these errors, // something is very broken. // // This error code will be generated by the gRPC framework in several // internal error conditions. Internal = 13; // Unavailable indicates the service is currently unavailable. // This is a most likely a transient condition and may be corrected // by retrying with a backoff. Note that it is not always safe to retry // non-idempotent operations. // // See litmus test above for deciding between FailedPrecondition, // Aborted, and Unavailable. // // This error code will be generated by the gRPC framework during // abrupt shutdown of a server process or network connection. Unavailable = 14; // DataLoss indicates unrecoverable data loss or corruption. // // This error code will not be generated by the gRPC framework. DataLoss = 15; // Unauthenticated indicates the request does not have valid // authentication credentials for the operation. // // The gRPC framework will generate this error code when the // authentication metadata is invalid or a Credentials callback fails, // but also expect authentication middleware to generate it. Unauthenticated = 16; } ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/types/sdk-go.types.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.17.3 // source: types/sdk-go.types.proto package types import ( code "github.com/kaydxh/golang/pkg/gocv/cgo/api/openapi-spec/types/code" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Symbols defined in public import of api/openapi-spec/types/code/sdk-go.code.proto. type Code = code.Code const Code_OK = code.Code_OK const Code_Canceled = code.Code_Canceled const Code_Unknown = code.Code_Unknown const Code_InvalidArgument = code.Code_InvalidArgument const Code_DeadlineExceeded = code.Code_DeadlineExceeded const Code_NotFound = code.Code_NotFound const Code_AlreadyExists = code.Code_AlreadyExists const Code_PermissionDenied = code.Code_PermissionDenied const Code_ResourceExhausted = code.Code_ResourceExhausted const Code_FailedPrecondition = code.Code_FailedPrecondition const Code_Aborted = code.Code_Aborted const Code_OutOfRange = code.Code_OutOfRange const Code_Unimplemented = code.Code_Unimplemented const Code_Internal = code.Code_Internal const Code_Unavailable = code.Code_Unavailable const Code_DataLoss = code.Code_DataLoss const Code_Unauthenticated = code.Code_Unauthenticated var Code_name = code.Code_name var Code_value = code.Code_value type CgoError = code.CgoError var File_types_sdk_go_types_proto protoreflect.FileDescriptor var file_types_sdk_go_types_proto_rawDesc = []byte{ 0x0a, 0x18, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x73, 0x64, 0x6b, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x1a, 0x2d, 0x61, 0x70, 0x69, 0x2f, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2d, 0x73, 0x70, 0x65, 0x63, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x2f, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x44, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x61, 0x79, 0x64, 0x78, 0x68, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x67, 0x6f, 0x63, 0x76, 0x2f, 0x63, 0x67, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2d, 0x73, 0x70, 0x65, 0x63, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x73, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var file_types_sdk_go_types_proto_goTypes = []interface{}{} var file_types_sdk_go_types_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_types_sdk_go_types_proto_init() } func file_types_sdk_go_types_proto_init() { if File_types_sdk_go_types_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_types_sdk_go_types_proto_rawDesc, NumEnums: 0, NumMessages: 0, NumExtensions: 0, NumServices: 0, }, GoTypes: file_types_sdk_go_types_proto_goTypes, DependencyIndexes: file_types_sdk_go_types_proto_depIdxs, }.Build() File_types_sdk_go_types_proto = out.File file_types_sdk_go_types_proto_rawDesc = nil file_types_sdk_go_types_proto_goTypes = nil file_types_sdk_go_types_proto_depIdxs = nil } ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/types/sdk-go.types.pb.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: api/openapi-spec/types/sdk-go.types.proto #ifndef PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2ftypes_2fsdk_2dgo_2etypes_2eproto #define PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2ftypes_2fsdk_2dgo_2etypes_2eproto #include #include #if GOOGLE_PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include #include #include #include #include #include #include #include // IWYU pragma: export #include // IWYU pragma: export #include "api/openapi-spec/types/code/sdk-go.code.pb.h" // IWYU pragma: export // @@protoc_insertion_point(includes) #define PROTOBUF_INTERNAL_EXPORT_protobuf_api_2fopenapi_2dspec_2ftypes_2fsdk_2dgo_2etypes_2eproto namespace protobuf_api_2fopenapi_2dspec_2ftypes_2fsdk_2dgo_2etypes_2eproto { // Internal implementation detail -- do not use these members. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[1]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; void AddDescriptors(); } // namespace protobuf_api_2fopenapi_2dspec_2ftypes_2fsdk_2dgo_2etypes_2eproto namespace sdk { namespace api { namespace types { } // namespace types } // namespace api } // namespace sdk namespace sdk { namespace api { namespace types { // =================================================================== // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace types } // namespace api } // namespace sdk // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_INCLUDED_api_2fopenapi_2dspec_2ftypes_2fsdk_2dgo_2etypes_2eproto ================================================ FILE: pkg/gocv/cgo/api/openapi-spec/types/sdk-go.types.proto ================================================ syntax = "proto3"; package sdk.api.types; import public "api/openapi-spec/types/code/sdk-go.code.proto"; option go_package = "github.com/kaydxh/golang/pkg/gocv/cgo/api/openapi-spec/types;types"; ================================================ FILE: pkg/gocv/cgo/cmake/FindProtobuf.cmake ================================================ macro(GENERATE_PROTOBUF_LIB IMPORT_DIRS DEPEND_TARGETS) if (IMPORT_DIRS) list(APPEND Protobuf_IMPORT_DIRS "${IMPORT_DIRS}") endif () get_filename_component(CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR} NAME) set(target ${CURRENT_FOLDER}) if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/third_path/protobuf/bin/protoc) set(Protobuf_PROTOC_EXECUTABLE ${CMAKE_CURRENT_SOURCE_DIR}/third_path/protobuf/bin/protoc) elseif (EXISTS ${PROJECT_SOURCE_DIR}/third_path/protobuf/bin/protoc) set(Protobuf_PROTOC_EXECUTABLE ${PROJECT_SOURCE_DIR}/third_path/protobuf/bin/protoc) elseif (EXISTS ${PROJECT_SOURCE_DIR}/third_party/protobuf/bin/protoc) set(Protobuf_PROTOC_EXECUTABLE ${PROJECT_SOURCE_DIR}/third_party/protobuf/bin/protoc) elseif (EXISTS ${PROJECT_SOURCE_DIR}/api/openapi-spec/third_path/protobuf/bin/protoc) set(Protobuf_PROTOC_EXECUTABLE ${PROJECT_SOURCE_DIR}/api/openapi-spec/third_path/protobuf/bin/protoc) else () message(SEND_ERROR "Error: protoc not found") return() endif () message(STATUS Protobuf_PROTOC_EXECUTABLE=${Protobuf_PROTOC_EXECUTABLE}) if (NOT TARGET protobuf::protoc) add_executable(protobuf::protoc IMPORTED) if (EXISTS "${Protobuf_PROTOC_EXECUTABLE}") set_target_properties(protobuf::protoc PROPERTIES IMPORTED_LOCATION "${Protobuf_PROTOC_EXECUTABLE}") endif () endif () set(protobuf_generate_LANGUAGE cpp) set(protobuf_generate_PROTOC_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}") set(Protobuf_USE_STATIC_LIBS ON) file(GLOB_RECURSE protofiles RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "*.proto") # PROTO_SRCS 存储.pb.cc文件的变量名称 # PROTO_HDRS 存储.pb.h文件的变量名称 # PROTOBUF_GENERATE_CPP generate *.h *.cxx files # https://github.com/protocolbuffers/protobuf/blob/main/cmake/protobuf-module.cmake.in PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS ${protofiles}) add_library(proto-${target} STATIC ${PROTO_SRCS} ${PROTO_HDRS}) target_include_directories(proto-${target} PUBLIC ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(proto-${target} PUBLIC protobuf ${DEPEND_TARGETS}) install(TARGETS proto-${target} OPTIONAL LIBRARY DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/ ARCHIVE DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/ RUNTIME DESTINATION DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/ ) foreach (_abs_file ${PROTO_HDRS}) file(RELATIVE_PATH _rel_file ${CMAKE_CURRENT_BINARY_DIR} ${_abs_file}) get_filename_component(_rel_dir ${_rel_file} DIRECTORY) install(FILES ${_abs_file} DESTINATION ${PROJECT_SOURCE_DIR}/${_rel_dir} OPTIONAL) endforeach () endmacro() macro(GET_MODEL_DIRS direction list_return) FILE(GLOB_RECURSE dirs LIST_DIRECTORIES true RELATIVE ${direction} ${direction}/*) SET(submodules_dirs) FOREACH (dir ${dirs}) IF(EXISTS ${direction}/${dir}/CMakeLists.txt) LIST(APPEND submodules_dirs ${direction}/${dir}) endif() ENDFOREACH() SET(${list_return} ${submodules_dirs}) endmacro() # This file contains backwards compatibility patches for various legacy functions and variables # Functions function(PROTOBUF_GENERATE_CPP SRCS HDRS) cmake_parse_arguments(protobuf_generate_cpp "" "EXPORT_MACRO" "" ${ARGN}) set(_proto_files "${protobuf_generate_cpp_UNPARSED_ARGUMENTS}") if(NOT _proto_files) message(SEND_ERROR "Error: PROTOBUF_GENERATE_CPP() called without any proto files") return() endif() if(PROTOBUF_GENERATE_CPP_APPEND_PATH) set(_append_arg APPEND_PATH) endif() if(DEFINED Protobuf_IMPORT_DIRS) set(_import_arg IMPORT_DIRS ${Protobuf_IMPORT_DIRS}) endif() set(_outvar) protobuf_generate(${_append_arg} LANGUAGE cpp EXPORT_MACRO ${protobuf_generate_cpp_EXPORT_MACRO} OUT_VAR _outvar ${_import_arg} PROTOS ${_proto_files}) set(${SRCS}) set(${HDRS}) foreach(_file ${_outvar}) if(_file MATCHES "cc$") list(APPEND ${SRCS} ${_file}) else() list(APPEND ${HDRS} ${_file}) endif() endforeach() set(${SRCS} ${${SRCS}} PARENT_SCOPE) set(${HDRS} ${${HDRS}} PARENT_SCOPE) endfunction() function(protobuf_generate) set(_options APPEND_PATH DESCRIPTORS) set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO PROTOC_OUT_DIR PLUGIN) if (COMMAND target_sources) list(APPEND _singleargs TARGET) endif () set(_multiargs PROTOS IMPORT_DIRS GENERATE_EXTENSIONS) cmake_parse_arguments(protobuf_generate "${_options}" "${_singleargs}" "${_multiargs}" "${ARGN}") if (NOT protobuf_generate_PROTOS AND NOT protobuf_generate_TARGET) message(SEND_ERROR "Error: protobuf_generate called without any targets or source files") return() endif () if (NOT protobuf_generate_OUT_VAR AND NOT protobuf_generate_TARGET) message(SEND_ERROR "Error: protobuf_generate called without a target or output variable") return() endif () if (NOT protobuf_generate_LANGUAGE) set(protobuf_generate_LANGUAGE cpp) endif () string(TOLOWER ${protobuf_generate_LANGUAGE} protobuf_generate_LANGUAGE) if (NOT protobuf_generate_PROTOC_OUT_DIR) set(protobuf_generate_PROTOC_OUT_DIR ${CMAKE_CURRENT_BINARY_DIR}) endif () if (protobuf_generate_EXPORT_MACRO AND protobuf_generate_LANGUAGE STREQUAL cpp) set(_dll_export_decl "dllexport_decl=${protobuf_generate_EXPORT_MACRO}:") endif () if (protobuf_generate_PLUGIN) set(_plugin "--plugin=${protobuf_generate_PLUGIN}") endif () if (NOT protobuf_generate_GENERATE_EXTENSIONS) if (protobuf_generate_LANGUAGE STREQUAL cpp) set(protobuf_generate_GENERATE_EXTENSIONS .pb.h .pb.cc) elseif (protobuf_generate_LANGUAGE STREQUAL python) set(protobuf_generate_GENERATE_EXTENSIONS _pb2.py) else () message(SEND_ERROR "Error: protobuf_generate given unknown Language ${LANGUAGE}, please provide a value for GENERATE_EXTENSIONS") return() endif () endif () if (protobuf_generate_TARGET) get_target_property(_source_list ${protobuf_generate_TARGET} SOURCES) foreach (_file ${_source_list}) if (_file MATCHES "proto$") list(APPEND protobuf_generate_PROTOS ${_file}) endif () endforeach () endif () if (NOT protobuf_generate_PROTOS) message(SEND_ERROR "Error: protobuf_generate could not find any .proto files") return() endif () if (protobuf_generate_APPEND_PATH) # Create an include path for each file specified foreach (_file ${protobuf_generate_PROTOS}) get_filename_component(_abs_file ${_file} ABSOLUTE) get_filename_component(_abs_path ${_abs_file} PATH) list(FIND _protobuf_include_path ${_abs_path} _contains_already) if (${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${_abs_path}) endif () endforeach () else () set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) endif () foreach (DIR ${protobuf_generate_IMPORT_DIRS}) get_filename_component(ABS_PATH ${DIR} ABSOLUTE) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if (${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif () endforeach () set(_generated_srcs_all) foreach (_proto ${protobuf_generate_PROTOS}) get_filename_component(_abs_file ${_proto} ABSOLUTE) get_filename_component(_abs_dir ${_abs_file} DIRECTORY) get_filename_component(_basename ${_proto} NAME_WLE) file(RELATIVE_PATH _rel_dir ${PROJECT_SOURCE_DIR} ${_abs_dir}) set(_possible_rel_dir) if (NOT protobuf_generate_APPEND_PATH) set(_possible_rel_dir ${_rel_dir}/) endif () set(_generated_srcs) foreach (_ext ${protobuf_generate_GENERATE_EXTENSIONS}) list(APPEND _generated_srcs "${protobuf_generate_PROTOC_OUT_DIR}/${_possible_rel_dir}${_basename}${_ext}") endforeach () if (protobuf_generate_DESCRIPTORS AND protobuf_generate_LANGUAGE STREQUAL cpp) set(_descriptor_file "${CMAKE_CURRENT_BINARY_DIR}/${_basename}.desc") set(_dll_desc_out "--descriptor_set_out=${_descriptor_file}") list(APPEND _generated_srcs ${_descriptor_file}) endif () list(APPEND _generated_srcs_all ${_generated_srcs}) file(RELATIVE_PATH _rel_proto_file ${PROJECT_SOURCE_DIR} ${_abs_file}) add_custom_command( OUTPUT ${_generated_srcs} COMMAND protobuf::protoc ARGS --${protobuf_generate_LANGUAGE}_out ${_dll_export_decl}${protobuf_generate_PROTOC_OUT_DIR} ${_plugin} ${_dll_desc_out} ${_protobuf_include_path} ${_rel_proto_file} WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} DEPENDS ${_abs_file} protobuf::protoc COMMENT "Running ${protobuf_generate_LANGUAGE} protocol buffer compiler on ${_proto}" VERBATIM) endforeach () set_source_files_properties(${_generated_srcs_all} PROPERTIES GENERATED TRUE) if (protobuf_generate_OUT_VAR) set(${protobuf_generate_OUT_VAR} ${_generated_srcs_all} PARENT_SCOPE) endif () if (protobuf_generate_TARGET) target_sources(${protobuf_generate_TARGET} PRIVATE ${_generated_srcs_all}) endif () endfunction() ================================================ FILE: pkg/gocv/cgo/gocv/Makefile ================================================ MAKEFILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) PROJECT_ROOT_DIR := $(realpath ${MAKEFILE_DIR}/..) PKG_CONFIG_PATH := ${PROJECT_ROOT_DIR}/pkgconfig SCRIPT_PATH := ${MAKEFILE_DIR}/../script TARGET := $(shell basename ${MAKEFILE_DIR}) # https://web.mit.edu/gnu/doc/html/make_8.html _empty:= # define space with $(_empty) _space:= $(_empty) $(_empty) define joinwith $(subst $(_space),$1,$(strip $2)) endef .PHONY: all all: deps generate test @echo "${MAKEFILE_DIR}" @echo "${PROJECT_ROOT_DIR}" @echo "${TARGET}" .PHONY: deps deps: @echo " > downloading deps library" .PHONY: version version: @bash -c "bash ${SCRIPT_PATH}/version.sh gitinfos" .PHONY: test test: version @$(eval THIRD_LIB_PATHS := $(shell find -L ${PROJECT_ROOT_DIR}/third_path/ -type d -iname "lib*" -print0 |xargs -0 -I {} bash -c 'echo {}'|grep -v "stubs")) @echo ${THIRD_LIB_PATHS} @$(eval JOINED_THIRD_LIB_PATHS := $(call joinwith,:,$(THIRD_LIB_PATHS))) PKG_CONFIG_PATH="${PKG_CONFIG_PATH}" LD_LIBRARY_PATH="$(JOINED_THIRD_LIB_PATHS):${LD_LIBRARY_PATH}" LIBRARY_PATH="$(JOINED_THIRD_LIB_PATHS):${LIBRARY_PATH}" go test -a -v . .PHONY: generate generate: @echo " > start to generate protocol buffers for target ${TARGET} in golang" @bash -c "go generate ../api/openapi-spec/proto.gen.go" @echo " > start to generate protocol buffers by cpp" @mkdir -p ${PROJECT_ROOT_DIR}/build; cd ${PROJECT_ROOT_DIR}/build; cmake .. --log-level "ERROR" @cmake --build ${PROJECT_ROOT_DIR}/build --target proto-${TARGET} -- -j `nproc`; @echo " > install generated protocol buffers by cpp" @cd ${PROJECT_ROOT_DIR}/build; cmake --install . ================================================ FILE: pkg/gocv/cgo/gocv/gocv.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 gocv import ( "os" "github.com/kaydxh/golang/pkg/gocv/cgo/api/openapi-spec/gocv" ) func NewMagickInitializeMagickRequest() *gocv.MagickInitializeMagickRequest { return &gocv.MagickInitializeMagickRequest{ Path: os.Args[0], } } func NewMagickImageDecodeRequest() *gocv.MagickImageDecodeRequest { return &gocv.MagickImageDecodeRequest{} } ================================================ FILE: pkg/gocv/cgo/gocv/gocv_test.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 gocv_test import ( "testing" io_ "github.com/kaydxh/golang/go/io" gocv_ "github.com/kaydxh/golang/pkg/gocv/cgo/gocv" ) func TestMagickInitializeMagick(t *testing.T) { } func TestMagickImageDecode(t *testing.T) { filename := "testdata/test.jpg" data, err := io_.ReadFile(filename) if err != nil { t.Error("Invalid ReadFile in TestMagickImageDecode") return } t.Logf("data size: %v", len(data)) req := gocv_.NewMagickImageDecodeRequest() req.Image = data resp, err := gocv_.MagickImageDecode(req) if err != nil { t.Error(err.Error()) return } t.Logf("resp: %v", resp) } ================================================ FILE: pkg/gocv/cgo/gocv/magick.h ================================================ #ifndef GOCV_MAGICK_H #define GOCV_MAGICK_H #ifdef __cplusplus extern "C" { #endif void sdk_gocv_magick_initialize_magick(void* req_data, int req_data_len, char** resp_data, int* resp_data_len); void sdk_gocv_magick_image_decode(void* req_data, int req_data_len, char** resp_data, int* resp_data_len); #ifdef __cplusplus } #endif #endif ================================================ FILE: pkg/gocv/cgo/gocv/magick_linux_amd64.cpp ================================================ #include #include #include "api/openapi-spec/gocv/gocv.magick.pb.h" #include "magick.h" void sdk_gocv_magick_initialize_magick(void* req_data, int req_data_len, char** resp_data, int* resp_data_len) { sdk::api::gocv::MagickInitializeMagickResponse resp; try { do { if (!resp_data) { resp.mutable_error()->set_error_code( sdk::types::code::Code::InvalidArgument); resp.mutable_error()->set_error_message("resp_data is nullptr"); break; } if (!resp_data_len) { resp.mutable_error()->set_error_code( sdk::types::code::Code::InvalidArgument); resp.mutable_error()->set_error_message( "pointer of resp_data_len is nullptr"); break; } sdk::api::gocv::MagickInitializeMagickRequest req; if (!req.ParseFromArray((char*)req_data, req_data_len)) { resp.mutable_error()->set_error_code( sdk::types::code::Code::InvalidArgument); resp.mutable_error()->set_error_message("ParseFromArray"); break; } if (req.path().empty()) { Magick::InitializeMagick(nullptr); } else { Magick::InitializeMagick(req.path().c_str()); } } while (0); } catch (const std::exception& e) { resp.mutable_error()->set_error_code(sdk::types::code::Code::Internal); resp.mutable_error()->set_error_message( "Magick::InitializeMagick exception:" + std::string(e.what())); } *resp_data_len = resp.ByteSize(); *resp_data = new char[*resp_data_len]; resp.SerializeToArray(*resp_data, *resp_data_len); } void sdk_gocv_magick_image_decode(void* req_data, int req_data_len, char** resp_data, int* resp_data_len) { sdk::api::gocv::MagickImageDecodeResponse resp; try { do { if (!resp_data) { resp.mutable_error()->set_error_code( sdk::types::code::Code::InvalidArgument); resp.mutable_error()->set_error_message("resp_data is nullptr"); break; } if (!resp_data_len) { resp.mutable_error()->set_error_code( sdk::types::code::Code::InvalidArgument); resp.mutable_error()->set_error_message( "pointer of resp_data_len is nullptr"); break; } sdk::api::gocv::MagickImageDecodeRequest req; if (!req.ParseFromArray((char*)req_data, req_data_len)) { resp.mutable_error()->set_error_code( sdk::types::code::Code::InvalidArgument); resp.mutable_error()->set_error_message("ParseFromArray"); break; } Magick::Image image; try { Magick::Blob blob((void*)(req.image().data()), req.image().length()); image.read(blob); } catch (Magick::Warning& w) { std::cout << "warn: " << w.what() << std::endl; // ignore warn } catch (Magick::Error& e) { std::cout << "a Magick++ error occurred: " << e.what() << std::endl; resp.mutable_error()->set_error_code( sdk::types::code::Code::Internal); resp.mutable_error()->set_error_message( "Magick::Blob read exception:" + std::string(e.what())); break; } catch (...) { std::cout << "an unhandled error has occurred" << std::endl; resp.mutable_error()->set_error_code( sdk::types::code::Code::Internal); resp.mutable_error()->set_error_message( "Magick::Blob read exception: an unhandled error has " "occurred"); break; } int rows = image.rows(); int columns = image.columns(); if (rows <= 0 || columns <= 0) { resp.mutable_error()->set_error_code( sdk::types::code::Code::InvalidArgument); resp.mutable_error()->set_error_message( std::string("invalid image resolution [") + std::to_string(columns) + std::string(" x ") + std::to_string(rows) + std::string("]")); break; } // https://www.imagemagick.org/Magick++/Image++.html cv::Mat mat; std::string map = req.target_color_space(); do { image.colorSpace(Magick::RGBColorspace); if (map == "BGR") { mat = ::cv::Mat(rows, columns, CV_8UC3); image.write(0, 0, columns, rows, "BGR", Magick::CharPixel, mat.data); break; } if (map == "BGRA") { mat = ::cv::Mat(rows, columns, CV_8UC4); image.write(0, 0, columns, rows, "BGRA", Magick::CharPixel, mat.data); break; } if (map == "GRAY") { image.type(Magick::GrayscaleType); mat = ::cv::Mat(rows, columns, CV_8UC3); image.write(0, 0, columns, rows, "BGR", Magick::CharPixel, mat.data); break; } if (map == "GRAYA") { image.type(Magick::GrayscaleMatteType); mat = ::cv::Mat(rows, columns, CV_8UC4); image.write(0, 0, columns, rows, "BGRA", Magick::CharPixel, mat.data); break; } mat = ::cv::Mat(rows, columns, CV_8UC4); image.write(0, 0, columns, rows, map, Magick::CharPixel, mat.data); } while (false); // set response resp.set_cv_mat_pointer(reinterpret_cast(new cv::Mat(mat))); resp.set_rows(image.rows()); resp.set_columns(image.columns()); resp.set_magick(image.magick()); resp.set_orientation_type( static_cast( image.orientation())); resp.set_colorspace_type( static_cast( image.colorSpace())); } while (0); } catch (const std::exception& e) { resp.mutable_error()->set_error_code(sdk::types::code::Code::Internal); resp.mutable_error()->set_error_message("Magick::Blob read exception:" + std::string(e.what())); } *resp_data_len = resp.ByteSize(); *resp_data = new char[*resp_data_len]; resp.SerializeToArray(*resp_data, *resp_data_len); } ================================================ FILE: pkg/gocv/cgo/gocv/magick_linux_amd64.go ================================================ /* *Copyright (c) 2022, kaydxh * *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 gocv /* #cgo pkg-config: protobuf opencv4 graphics-magick #cgo CXXFLAGS: -std=c++11 -I${SRCDIR}/.. #cgo LDFLAGS: -L${SRCDIR}/../api/openapi-spec/gocv/ -lproto-gocv #cgo LDFLAGS: -L${SRCDIR}/../api/openapi-spec/types/ -lproto-types #include #include "magick.h" */ import "C" import ( "sync" "unsafe" unsafe_ "github.com/kaydxh/golang/go/unsafe" gocvpb "github.com/kaydxh/golang/pkg/gocv/cgo/api/openapi-spec/gocv" "google.golang.org/protobuf/proto" ) var once sync.Once func init() { err := MagickInitializeMagick(nil) if err != nil { panic(err) } } func MagickInitializeMagick(req *gocvpb.MagickInitializeMagickRequest) error { var errOnce error once.Do(func() { reqData, err := proto.Marshal(req) if err != nil { errOnce = err return } var respData *C.char var respDataLen C.int defer func() { C.free(unsafe.Pointer(respData)) respData = nil }() C.sdk_gocv_magick_initialize_magick( unsafe_.BytesPointer(reqData), C.int(len(reqData)), &respData, &respDataLen, ) var resp gocvpb.MagickInitializeMagickResponse err = proto.Unmarshal(C.GoBytes(unsafe.Pointer(respData), C.int(respDataLen)), &resp) if err != nil { errOnce = err return } if resp.GetError() != nil { errOnce = resp.GetError() return } errOnce = nil return }) return errOnce } func MagickImageDecode(req *gocvpb.MagickImageDecodeRequest) (*gocvpb.MagickImageDecodeResponse, error) { reqData, err := proto.Marshal(req) if err != nil { return nil, err } var respData *C.char var respDataLen C.int defer func() { C.free(unsafe.Pointer(respData)) respData = nil }() C.sdk_gocv_magick_image_decode(unsafe_.BytesPointer(reqData), C.int(len(reqData)), &respData, &respDataLen) var resp gocvpb.MagickImageDecodeResponse err = proto.Unmarshal(C.GoBytes(unsafe.Pointer(respData), C.int(respDataLen)), &resp) if err != nil { return nil, err } if resp.GetError() != nil { return nil, resp.GetError() } return &resp, nil } ================================================ FILE: pkg/gocv/cgo/pkgconfig/graphics-magick.pc ================================================ prefix=${pcfiledir}/../third_path/graphics-magick libdir=${prefix}/lib includedir=${prefix}/include Name: GraphicsMagick Description: GraphicsMagick Image Processing Library Version: 1.3.35 Libs: -L${libdir} -lGraphicsMagick++ -lGraphicsMagick Cflags: -I${includedir} ================================================ FILE: pkg/gocv/cgo/pkgconfig/opencv2.pc ================================================ prefix=${pcfiledir}/../third_path/opencv2/ exec_prefix=${prefix} Name: OpenCV Description: Open Source Computer Vision Library Version: 2.4.12 Libs: -L${exec_prefix}/lib -L${exec_prefix}/lib64 -lopencv_calib3d -lopencv_contrib -lopencv_core -lopencv_features2d -lopencv_flann -lopencv_gpu -lopencv_highgui -lopencv_imgproc -lopencv_legacy -lopencv_ml -lopencv_nonfree -lopencv_objdetect -lopencv_ocl -lopencv_photo -lopencv_stitching -lopencv_superres -lopencv_ts -lopencv_video -lopencv_videostab -lrt -lpthread -lm -ldl Cflags: -I${prefix}/include/opencv -I${prefix}/include ================================================ FILE: pkg/gocv/cgo/pkgconfig/opencv4.pc ================================================ prefix=${pcfiledir}/../third_path/opencv4/ exec_prefix=${prefix} Name: OpenCV Description: Open Source Computer Vision Library Version: 4.3.0 Libs: -L${exec_prefix}/lib64 -lopencv_calib3d -lopencv_core -lopencv_dnn -lopencv_features2d -lopencv_flann -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lopencv_ml -lopencv_objdetect -lopencv_photo -lopencv_stitching -lopencv_videoio -lopencv_video -lrt -lpthread -lm -ldl Cflags: -I${prefix}/include/opencv -I${prefix}/include ================================================ FILE: pkg/gocv/cgo/pkgconfig/protobuf.pc ================================================ prefix=${pcfiledir}/../third_path/protobuf exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: Protocol Buffers Description: Google's Data Interchange Format Version: 3.6.1 Libs: -L${libdir} -lprotobuf -pthread Libs.private: -lz Cflags: -I${includedir} -pthread Conflicts: protobuf-lite ================================================ FILE: pkg/gocv/cgo/pkgconfig/pybind11.pc ================================================ prefix=${pcfiledir}/../third_path/pybind11 exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: pybind11 Description: Seamless operability between C++11 and Python Version: 2.10.4 Libs: #-L${libdir} -lprotobuf -pthread Libs.private: -lz Cflags: -I${includedir} #-pthread Requires: python3-embed ================================================ FILE: pkg/gocv/cgo/pkgconfig/python3-embed.pc ================================================ # See: man pkg-config prefix=/usr exec_prefix=/usr libdir=/usr/lib64 includedir=/usr/include Name: Python Description: Embed Python into an application Requires: Version: 3.8 Libs.private: -lcrypt -lpthread -ldl -lutil -lm Libs: -L${libdir} -lpython3.8 Cflags: -I${includedir}/python3.8 ================================================ FILE: pkg/gocv/cgo/script/version.sh ================================================ #!/usr/bin/env bash # exit by command return non-zero exit code set -o errexit # Indicate an error when it encounters an undefined variable set -o nounset # Fail on any error. set -o pipefail # set -o xtrace function get_version_from_git() { GIT="git" GIT_COMMIT=$("${GIT}" rev-parse "HEAD^{commit}") GIT_TAG=$(git describe --long --tags --dirty --tags --always) GIT_BUILD_TIME=$(TZ=UTC date -u '+%Y-%m-%dT%H:%M:%SZ') GIT_DIRTY=$(test -n "`git status --porcelain`" && echo "+CHANGES" || true) GIT_TREE_STATE=${GIT_TREE_STATE-} if git_status=$("${GIT}" status --porcelain) && [[ -z ${git_status} ]]; then GIT_TREE_STATE="clean" else GIT_TREE_STATE="dirty" fi } function gitinfos() { get_version_from_git local -a gitinfos function add_gitinfo() { local key=${1} local val=${2} # update the list github.com/kaydxh/golang/pkg/app. gitinfos+=( "${key}=${val}" ) } add_gitinfo "buildDate" "${GIT_BUILD_TIME}" add_gitinfo "gitVersion" "${GIT_TAG}" add_gitinfo "gitCommit" "${GIT_COMMIT}" add_gitinfo "gitTreeState" "${GIT_TREE_STATE}" # "$*" => get arg1 arg2 arg3 as a single argument "a1 a2 a3" # "$@" => gets arg1, arg2 and arg3 as a separate arguments "a1" "a2" "a3" # if no quotes, $* is the same to $@, as a separate arguments "a1" "a2" "a3" for gitinfo in "${gitinfos[@]}" do echo ${gitinfo} done } # Allows to call a function based on arguments passed to the script $* ================================================ FILE: pkg/gocv/cgo/swig/gocv/Makefile ================================================ MAKEFILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) PROJECT_ROOT_DIR := $(realpath ${MAKEFILE_DIR}/../..) PKG_CONFIG_PATH := ${PROJECT_ROOT_DIR}/pkgconfig SCRIPT_PATH := ${MAKEFILE_DIR}/../../script TARGET := $(shell basename ${MAKEFILE_DIR}) # https://web.mit.edu/gnu/doc/html/make_8.html _empty:= # define space with $(_empty) _space:= $(_empty) $(_empty) define joinwith $(subst $(_space),$1,$(strip $2)) endef .PHONY: all all: deps generate test @echo "${MAKEFILE_DIR}" @echo "${PROJECT_ROOT_DIR}" @echo "${TARGET}" .PHONY: deps deps: @echo " > downloading deps library" .PHONY: version version: @bash -c "bash ${SCRIPT_PATH}/version.sh gitinfos" .PHONY: test test: version @$(eval THIRD_LIB_PATHS := $(shell find -L ${PROJECT_ROOT_DIR}/third_path/ -type d -iname "lib*" -print0 |xargs -0 -I {} bash -c 'echo {}'|grep -v "stubs")) @echo ${THIRD_LIB_PATHS} @$(eval JOINED_THIRD_LIB_PATHS := $(call joinwith,:,$(THIRD_LIB_PATHS))) PKG_CONFIG_PATH="${PKG_CONFIG_PATH}" LD_LIBRARY_PATH="$(JOINED_THIRD_LIB_PATHS):${LD_LIBRARY_PATH}" LIBRARY_PATH="$(JOINED_THIRD_LIB_PATHS):${LIBRARY_PATH}" go test -a -v . .PHONY: generate generate: ================================================ FILE: pkg/gocv/cgo/swig/gocv/cgo.go ================================================ package gocv /* #cgo linux,amd64 pkg-config: opencv4 graphics-magick #cgo !linux !amd64 CXXFLAGS: -D__CGO_UNKNOWN_PLATFORM__ #cgo CXXFLAGS: -std=c++11 #include */ import "C" ================================================ FILE: pkg/gocv/cgo/swig/gocv/gocv.go ================================================ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (https://www.swig.org). * Version 4.1.1 * * Do not make changes to this file unless you know what you are doing - modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ // source: gocv.swigcxx package gocv /* #define intgo swig_intgo typedef void *swig_voidp; #include #include typedef long long intgo; typedef unsigned long long uintgo; typedef struct { char *p; intgo n; } _gostring_; typedef struct { void* array; intgo len; intgo cap; } _goslice_; typedef _gostring_ swig_type_1; typedef _gostring_ swig_type_2; typedef _gostring_ swig_type_3; typedef _gostring_ swig_type_4; typedef _gostring_ swig_type_5; typedef _gostring_ swig_type_6; typedef _gostring_ swig_type_7; typedef _gostring_ swig_type_8; extern void _wrap_Swig_free_gocv_ba346308b44e7b91(uintptr_t arg1); extern uintptr_t _wrap_Swig_malloc_gocv_ba346308b44e7b91(swig_intgo arg1); extern void _wrap_MagickInitializeMagickRequest_path_set_gocv_ba346308b44e7b91(uintptr_t arg1, swig_type_1 arg2); extern swig_type_2 _wrap_MagickInitializeMagickRequest_path_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern uintptr_t _wrap_new_MagickInitializeMagickRequest_gocv_ba346308b44e7b91(void); extern void _wrap_delete_MagickInitializeMagickRequest_gocv_ba346308b44e7b91(uintptr_t arg1); extern uintptr_t _wrap_new_MagickInitializeMagickResponse_gocv_ba346308b44e7b91(void); extern void _wrap_delete_MagickInitializeMagickResponse_gocv_ba346308b44e7b91(uintptr_t arg1); extern void _wrap_MagickImageDecodeRequest_image_set_gocv_ba346308b44e7b91(uintptr_t arg1, swig_type_3 arg2); extern swig_type_4 _wrap_MagickImageDecodeRequest_image_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern void _wrap_MagickImageDecodeRequest_target_color_space_set_gocv_ba346308b44e7b91(uintptr_t arg1, swig_type_5 arg2); extern swig_type_6 _wrap_MagickImageDecodeRequest_target_color_space_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern uintptr_t _wrap_new_MagickImageDecodeRequest_gocv_ba346308b44e7b91(void); extern void _wrap_delete_MagickImageDecodeRequest_gocv_ba346308b44e7b91(uintptr_t arg1); extern swig_intgo _wrap_UndefinedOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_TopLeftOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_TopRightOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_BottomRightOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_BottomLeftOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_LeftTopOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_RightTopOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_RightBottomOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_LeftBottomOrientation_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_UndefinedColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_RGBColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_GRAYColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_TransparentColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_OHTAColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_XYZColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_YCCColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_YIQColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_YPbPrColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_YUVColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_CMYKColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_sRGBColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_HSLColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_HWBColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_LABColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_CineonLogRGBColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_Rec601LumaColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_Rec601YCbCrColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_Rec709LumaColorspace_gocv_ba346308b44e7b91(void); extern swig_intgo _wrap_Rec709YCbCrColorspace_gocv_ba346308b44e7b91(void); extern void _wrap_MagickImageDecodeResponse_mat_set_gocv_ba346308b44e7b91(uintptr_t arg1, uintptr_t arg2); extern uintptr_t _wrap_MagickImageDecodeResponse_mat_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern void _wrap_MagickImageDecodeResponse_rows_set_gocv_ba346308b44e7b91(uintptr_t arg1, swig_intgo arg2); extern swig_intgo _wrap_MagickImageDecodeResponse_rows_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern void _wrap_MagickImageDecodeResponse_columns_set_gocv_ba346308b44e7b91(uintptr_t arg1, swig_intgo arg2); extern swig_intgo _wrap_MagickImageDecodeResponse_columns_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern void _wrap_MagickImageDecodeResponse_magick_set_gocv_ba346308b44e7b91(uintptr_t arg1, swig_type_7 arg2); extern swig_type_8 _wrap_MagickImageDecodeResponse_magick_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern void _wrap_MagickImageDecodeResponse_orientation_type_set_gocv_ba346308b44e7b91(uintptr_t arg1, swig_intgo arg2); extern swig_intgo _wrap_MagickImageDecodeResponse_orientation_type_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern void _wrap_MagickImageDecodeResponse_colorspace_type_set_gocv_ba346308b44e7b91(uintptr_t arg1, swig_intgo arg2); extern swig_intgo _wrap_MagickImageDecodeResponse_colorspace_type_get_gocv_ba346308b44e7b91(uintptr_t arg1); extern uintptr_t _wrap_new_MagickImageDecodeResponse_gocv_ba346308b44e7b91(void); extern void _wrap_delete_MagickImageDecodeResponse_gocv_ba346308b44e7b91(uintptr_t arg1); extern uintptr_t _wrap_new_Wrapped_MagicImage_gocv_ba346308b44e7b91(void); extern void _wrap_delete_Wrapped_MagicImage_gocv_ba346308b44e7b91(uintptr_t arg1); extern void _wrap_Wrapped_MagicImage_MagickInitializeMagick_gocv_ba346308b44e7b91(uintptr_t arg1, uintptr_t arg2); extern void _wrap_Wrapped_MagicImage_Wrapped_MagickImageDecode_gocv_ba346308b44e7b91(uintptr_t arg1, uintptr_t arg2, uintptr_t arg3); #undef intgo */ import "C" import "unsafe" import _ "runtime/cgo" import "sync" import "fmt" type _ unsafe.Pointer var Swig_escape_always_false bool var Swig_escape_val interface{} type _swig_fnptr *byte type _swig_memberptr *byte func getSwigcptr(v interface { Swigcptr() uintptr }) uintptr { if v == nil { return 0 } return v.Swigcptr() } type _ sync.Mutex //export cgo_panic__gocv_ba346308b44e7b91 func cgo_panic__gocv_ba346308b44e7b91(p *byte) { s := (*[1024]byte)(unsafe.Pointer(p))[:] for i, b := range s { if b == 0 { panic(string(s[:i])) } } panic(string(s)) } type swig_gostring struct { p uintptr; n int } func swigCopyString(s string) string { p := *(*swig_gostring)(unsafe.Pointer(&s)) r := string((*[0x7fffffff]byte)(unsafe.Pointer(p.p))[:p.n]) Swig_free(p.p) return r } func Swig_free(arg1 uintptr) { _swig_i_0 := arg1 C._wrap_Swig_free_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) } func Swig_malloc(arg1 int) (_swig_ret uintptr) { var swig_r uintptr _swig_i_0 := arg1 swig_r = (uintptr)(C._wrap_Swig_malloc_gocv_ba346308b44e7b91(C.swig_intgo(_swig_i_0))) return swig_r } type SwigcptrMagickInitializeMagickRequest uintptr func (p SwigcptrMagickInitializeMagickRequest) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrMagickInitializeMagickRequest) SwigIsMagickInitializeMagickRequest() { } func (arg1 SwigcptrMagickInitializeMagickRequest) SetPath(arg2 string) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_MagickInitializeMagickRequest_path_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), *(*C.swig_type_1)(unsafe.Pointer(&_swig_i_1))) if Swig_escape_always_false { Swig_escape_val = arg2 } } func (arg1 SwigcptrMagickInitializeMagickRequest) GetPath() (_swig_ret string) { var swig_r string _swig_i_0 := arg1 swig_r_p := C._wrap_MagickInitializeMagickRequest_path_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) swig_r = *(*string)(unsafe.Pointer(&swig_r_p)) var swig_r_1 string swig_r_1 = swigCopyString(swig_r) return swig_r_1 } func NewMagickInitializeMagickRequest() (_swig_ret MagickInitializeMagickRequest) { var swig_r MagickInitializeMagickRequest swig_r = (MagickInitializeMagickRequest)(SwigcptrMagickInitializeMagickRequest(C._wrap_new_MagickInitializeMagickRequest_gocv_ba346308b44e7b91())) return swig_r } func DeleteMagickInitializeMagickRequest(arg1 MagickInitializeMagickRequest) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_MagickInitializeMagickRequest_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) } type MagickInitializeMagickRequest interface { Swigcptr() uintptr SwigIsMagickInitializeMagickRequest() SetPath(arg2 string) GetPath() (_swig_ret string) } type SwigcptrMagickInitializeMagickResponse uintptr func (p SwigcptrMagickInitializeMagickResponse) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrMagickInitializeMagickResponse) SwigIsMagickInitializeMagickResponse() { } func NewMagickInitializeMagickResponse() (_swig_ret MagickInitializeMagickResponse) { var swig_r MagickInitializeMagickResponse swig_r = (MagickInitializeMagickResponse)(SwigcptrMagickInitializeMagickResponse(C._wrap_new_MagickInitializeMagickResponse_gocv_ba346308b44e7b91())) return swig_r } func DeleteMagickInitializeMagickResponse(arg1 MagickInitializeMagickResponse) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_MagickInitializeMagickResponse_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) } type MagickInitializeMagickResponse interface { Swigcptr() uintptr SwigIsMagickInitializeMagickResponse() } type SwigcptrMagickImageDecodeRequest uintptr func (p SwigcptrMagickImageDecodeRequest) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrMagickImageDecodeRequest) SwigIsMagickImageDecodeRequest() { } func (arg1 SwigcptrMagickImageDecodeRequest) SetImage(arg2 string) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_MagickImageDecodeRequest_image_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), *(*C.swig_type_3)(unsafe.Pointer(&_swig_i_1))) if Swig_escape_always_false { Swig_escape_val = arg2 } } func (arg1 SwigcptrMagickImageDecodeRequest) GetImage() (_swig_ret string) { var swig_r string _swig_i_0 := arg1 swig_r_p := C._wrap_MagickImageDecodeRequest_image_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) swig_r = *(*string)(unsafe.Pointer(&swig_r_p)) var swig_r_1 string swig_r_1 = swigCopyString(swig_r) return swig_r_1 } func (arg1 SwigcptrMagickImageDecodeRequest) SetTarget_color_space(arg2 string) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_MagickImageDecodeRequest_target_color_space_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), *(*C.swig_type_5)(unsafe.Pointer(&_swig_i_1))) if Swig_escape_always_false { Swig_escape_val = arg2 } } func (arg1 SwigcptrMagickImageDecodeRequest) GetTarget_color_space() (_swig_ret string) { var swig_r string _swig_i_0 := arg1 swig_r_p := C._wrap_MagickImageDecodeRequest_target_color_space_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) swig_r = *(*string)(unsafe.Pointer(&swig_r_p)) var swig_r_1 string swig_r_1 = swigCopyString(swig_r) return swig_r_1 } func NewMagickImageDecodeRequest() (_swig_ret MagickImageDecodeRequest) { var swig_r MagickImageDecodeRequest swig_r = (MagickImageDecodeRequest)(SwigcptrMagickImageDecodeRequest(C._wrap_new_MagickImageDecodeRequest_gocv_ba346308b44e7b91())) return swig_r } func DeleteMagickImageDecodeRequest(arg1 MagickImageDecodeRequest) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_MagickImageDecodeRequest_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) } type MagickImageDecodeRequest interface { Swigcptr() uintptr SwigIsMagickImageDecodeRequest() SetImage(arg2 string) GetImage() (_swig_ret string) SetTarget_color_space(arg2 string) GetTarget_color_space() (_swig_ret string) } type GocvOrientationType int func _swig_getUndefinedOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_UndefinedOrientation_gocv_ba346308b44e7b91()) return swig_r } var UndefinedOrientation GocvOrientationType = _swig_getUndefinedOrientation() func _swig_getTopLeftOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_TopLeftOrientation_gocv_ba346308b44e7b91()) return swig_r } var TopLeftOrientation GocvOrientationType = _swig_getTopLeftOrientation() func _swig_getTopRightOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_TopRightOrientation_gocv_ba346308b44e7b91()) return swig_r } var TopRightOrientation GocvOrientationType = _swig_getTopRightOrientation() func _swig_getBottomRightOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_BottomRightOrientation_gocv_ba346308b44e7b91()) return swig_r } var BottomRightOrientation GocvOrientationType = _swig_getBottomRightOrientation() func _swig_getBottomLeftOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_BottomLeftOrientation_gocv_ba346308b44e7b91()) return swig_r } var BottomLeftOrientation GocvOrientationType = _swig_getBottomLeftOrientation() func _swig_getLeftTopOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_LeftTopOrientation_gocv_ba346308b44e7b91()) return swig_r } var LeftTopOrientation GocvOrientationType = _swig_getLeftTopOrientation() func _swig_getRightTopOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_RightTopOrientation_gocv_ba346308b44e7b91()) return swig_r } var RightTopOrientation GocvOrientationType = _swig_getRightTopOrientation() func _swig_getRightBottomOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_RightBottomOrientation_gocv_ba346308b44e7b91()) return swig_r } var RightBottomOrientation GocvOrientationType = _swig_getRightBottomOrientation() func _swig_getLeftBottomOrientation() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType swig_r = (GocvOrientationType)(C._wrap_LeftBottomOrientation_gocv_ba346308b44e7b91()) return swig_r } var LeftBottomOrientation GocvOrientationType = _swig_getLeftBottomOrientation() type GocvColorspaceType int func _swig_getUndefinedColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_UndefinedColorspace_gocv_ba346308b44e7b91()) return swig_r } var UndefinedColorspace GocvColorspaceType = _swig_getUndefinedColorspace() func _swig_getRGBColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_RGBColorspace_gocv_ba346308b44e7b91()) return swig_r } var RGBColorspace GocvColorspaceType = _swig_getRGBColorspace() func _swig_getGRAYColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_GRAYColorspace_gocv_ba346308b44e7b91()) return swig_r } var GRAYColorspace GocvColorspaceType = _swig_getGRAYColorspace() func _swig_getTransparentColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_TransparentColorspace_gocv_ba346308b44e7b91()) return swig_r } var TransparentColorspace GocvColorspaceType = _swig_getTransparentColorspace() func _swig_getOHTAColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_OHTAColorspace_gocv_ba346308b44e7b91()) return swig_r } var OHTAColorspace GocvColorspaceType = _swig_getOHTAColorspace() func _swig_getXYZColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_XYZColorspace_gocv_ba346308b44e7b91()) return swig_r } var XYZColorspace GocvColorspaceType = _swig_getXYZColorspace() func _swig_getYCCColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_YCCColorspace_gocv_ba346308b44e7b91()) return swig_r } var YCCColorspace GocvColorspaceType = _swig_getYCCColorspace() func _swig_getYIQColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_YIQColorspace_gocv_ba346308b44e7b91()) return swig_r } var YIQColorspace GocvColorspaceType = _swig_getYIQColorspace() func _swig_getYPbPrColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_YPbPrColorspace_gocv_ba346308b44e7b91()) return swig_r } var YPbPrColorspace GocvColorspaceType = _swig_getYPbPrColorspace() func _swig_getYUVColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_YUVColorspace_gocv_ba346308b44e7b91()) return swig_r } var YUVColorspace GocvColorspaceType = _swig_getYUVColorspace() func _swig_getCMYKColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_CMYKColorspace_gocv_ba346308b44e7b91()) return swig_r } var CMYKColorspace GocvColorspaceType = _swig_getCMYKColorspace() func _swig_getsRGBColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_sRGBColorspace_gocv_ba346308b44e7b91()) return swig_r } var SRGBColorspace GocvColorspaceType = _swig_getsRGBColorspace() func _swig_getHSLColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_HSLColorspace_gocv_ba346308b44e7b91()) return swig_r } var HSLColorspace GocvColorspaceType = _swig_getHSLColorspace() func _swig_getHWBColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_HWBColorspace_gocv_ba346308b44e7b91()) return swig_r } var HWBColorspace GocvColorspaceType = _swig_getHWBColorspace() func _swig_getLABColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_LABColorspace_gocv_ba346308b44e7b91()) return swig_r } var LABColorspace GocvColorspaceType = _swig_getLABColorspace() func _swig_getCineonLogRGBColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_CineonLogRGBColorspace_gocv_ba346308b44e7b91()) return swig_r } var CineonLogRGBColorspace GocvColorspaceType = _swig_getCineonLogRGBColorspace() func _swig_getRec601LumaColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_Rec601LumaColorspace_gocv_ba346308b44e7b91()) return swig_r } var Rec601LumaColorspace GocvColorspaceType = _swig_getRec601LumaColorspace() func _swig_getRec601YCbCrColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_Rec601YCbCrColorspace_gocv_ba346308b44e7b91()) return swig_r } var Rec601YCbCrColorspace GocvColorspaceType = _swig_getRec601YCbCrColorspace() func _swig_getRec709LumaColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_Rec709LumaColorspace_gocv_ba346308b44e7b91()) return swig_r } var Rec709LumaColorspace GocvColorspaceType = _swig_getRec709LumaColorspace() func _swig_getRec709YCbCrColorspace() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType swig_r = (GocvColorspaceType)(C._wrap_Rec709YCbCrColorspace_gocv_ba346308b44e7b91()) return swig_r } var Rec709YCbCrColorspace GocvColorspaceType = _swig_getRec709YCbCrColorspace() type SwigcptrMagickImageDecodeResponse uintptr func (p SwigcptrMagickImageDecodeResponse) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrMagickImageDecodeResponse) SwigIsMagickImageDecodeResponse() { } func (arg1 SwigcptrMagickImageDecodeResponse) SetMat(arg2 Cv_Mat) { _swig_i_0 := arg1 _swig_i_1 := getSwigcptr(arg2) C._wrap_MagickImageDecodeResponse_mat_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), C.uintptr_t(_swig_i_1)) } func (arg1 SwigcptrMagickImageDecodeResponse) GetMat() (_swig_ret Cv_Mat) { var swig_r Cv_Mat _swig_i_0 := arg1 swig_r = (Cv_Mat)(SwigcptrCv_Mat(C._wrap_MagickImageDecodeResponse_mat_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)))) return swig_r } func (arg1 SwigcptrMagickImageDecodeResponse) SetRows(arg2 int) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_MagickImageDecodeResponse_rows_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), C.swig_intgo(_swig_i_1)) } func (arg1 SwigcptrMagickImageDecodeResponse) GetRows() (_swig_ret int) { var swig_r int _swig_i_0 := arg1 swig_r = (int)(C._wrap_MagickImageDecodeResponse_rows_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0))) return swig_r } func (arg1 SwigcptrMagickImageDecodeResponse) SetColumns(arg2 int) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_MagickImageDecodeResponse_columns_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), C.swig_intgo(_swig_i_1)) } func (arg1 SwigcptrMagickImageDecodeResponse) GetColumns() (_swig_ret int) { var swig_r int _swig_i_0 := arg1 swig_r = (int)(C._wrap_MagickImageDecodeResponse_columns_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0))) return swig_r } func (arg1 SwigcptrMagickImageDecodeResponse) SetMagick(arg2 string) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_MagickImageDecodeResponse_magick_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), *(*C.swig_type_7)(unsafe.Pointer(&_swig_i_1))) if Swig_escape_always_false { Swig_escape_val = arg2 } } func (arg1 SwigcptrMagickImageDecodeResponse) GetMagick() (_swig_ret string) { var swig_r string _swig_i_0 := arg1 swig_r_p := C._wrap_MagickImageDecodeResponse_magick_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) swig_r = *(*string)(unsafe.Pointer(&swig_r_p)) var swig_r_1 string swig_r_1 = swigCopyString(swig_r) return swig_r_1 } func (arg1 SwigcptrMagickImageDecodeResponse) SetOrientation_type(arg2 GocvOrientationType) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_MagickImageDecodeResponse_orientation_type_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), C.swig_intgo(_swig_i_1)) } func (arg1 SwigcptrMagickImageDecodeResponse) GetOrientation_type() (_swig_ret GocvOrientationType) { var swig_r GocvOrientationType _swig_i_0 := arg1 swig_r = (GocvOrientationType)(C._wrap_MagickImageDecodeResponse_orientation_type_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0))) return swig_r } func (arg1 SwigcptrMagickImageDecodeResponse) SetColorspace_type(arg2 GocvColorspaceType) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_MagickImageDecodeResponse_colorspace_type_set_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), C.swig_intgo(_swig_i_1)) } func (arg1 SwigcptrMagickImageDecodeResponse) GetColorspace_type() (_swig_ret GocvColorspaceType) { var swig_r GocvColorspaceType _swig_i_0 := arg1 swig_r = (GocvColorspaceType)(C._wrap_MagickImageDecodeResponse_colorspace_type_get_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0))) return swig_r } func NewMagickImageDecodeResponse() (_swig_ret MagickImageDecodeResponse) { var swig_r MagickImageDecodeResponse swig_r = (MagickImageDecodeResponse)(SwigcptrMagickImageDecodeResponse(C._wrap_new_MagickImageDecodeResponse_gocv_ba346308b44e7b91())) return swig_r } func DeleteMagickImageDecodeResponse(arg1 MagickImageDecodeResponse) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_MagickImageDecodeResponse_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) } type MagickImageDecodeResponse interface { Swigcptr() uintptr SwigIsMagickImageDecodeResponse() SetMat(arg2 Cv_Mat) GetMat() (_swig_ret Cv_Mat) SetRows(arg2 int) GetRows() (_swig_ret int) SetColumns(arg2 int) GetColumns() (_swig_ret int) SetMagick(arg2 string) GetMagick() (_swig_ret string) SetOrientation_type(arg2 GocvOrientationType) GetOrientation_type() (_swig_ret GocvOrientationType) SetColorspace_type(arg2 GocvColorspaceType) GetColorspace_type() (_swig_ret GocvColorspaceType) } type SwigcptrWrapped_MagicImage uintptr func (p SwigcptrWrapped_MagicImage) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrWrapped_MagicImage) SwigIsWrapped_MagicImage() { } func NewWrapped_MagicImage() (_swig_ret Wrapped_MagicImage) { var swig_r Wrapped_MagicImage swig_r = (Wrapped_MagicImage)(SwigcptrWrapped_MagicImage(C._wrap_new_Wrapped_MagicImage_gocv_ba346308b44e7b91())) return swig_r } func DeleteWrapped_MagicImage(arg1 Wrapped_MagicImage) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_Wrapped_MagicImage_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0)) } func Wrapped_MagicImageMagickInitializeMagick(arg1 MagickInitializeMagickRequest, arg2 MagickInitializeMagickResponse) { _swig_i_0 := getSwigcptr(arg1) _swig_i_1 := getSwigcptr(arg2) C._wrap_Wrapped_MagicImage_MagickInitializeMagick_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), C.uintptr_t(_swig_i_1)) } func (arg1 SwigcptrWrapped_MagicImage) Wrapped_MagickImageDecode(arg2 MagickImageDecodeRequest, arg3 MagickImageDecodeResponse) { _swig_i_0 := arg1 _swig_i_1 := getSwigcptr(arg2) _swig_i_2 := getSwigcptr(arg3) C._wrap_Wrapped_MagicImage_Wrapped_MagickImageDecode_gocv_ba346308b44e7b91(C.uintptr_t(_swig_i_0), C.uintptr_t(_swig_i_1), C.uintptr_t(_swig_i_2)) } type Wrapped_MagicImage interface { Swigcptr() uintptr SwigIsWrapped_MagicImage() Wrapped_MagickImageDecode(arg2 MagickImageDecodeRequest, arg3 MagickImageDecodeResponse) } type MagicImage interface { Wrapped_MagicImage MagickImageDecode(MagickImageDecodeRequest) (MagickImageDecodeResponse, error) } func NewMagicImage() MagicImage { mi := NewWrapped_MagicImage() return mi.(MagicImage) } // catch will recover from a panic and store the recover message to the error // parameter. The error must be passed by reference in order to be returned to the // calling function. func catch(err *error) { if r := recover(); r != nil { *err = fmt.Errorf("%v", r) } } func MagickInitializeMagick(req MagickInitializeMagickRequest) (resp MagickInitializeMagickResponse, err error) { defer catch(&err) resp = NewMagickInitializeMagickResponse() Wrapped_MagicImageMagickInitializeMagick(req, resp) return } func (arg SwigcptrWrapped_MagicImage) MagickImageDecode(req MagickImageDecodeRequest) (resp MagickImageDecodeResponse, err error) { defer catch(&err) resp = NewMagickImageDecodeResponse() arg.Wrapped_MagickImageDecode(req, resp) return } type SwigcptrCv_Mat uintptr type Cv_Mat interface { Swigcptr() uintptr; } func (p SwigcptrCv_Mat) Swigcptr() uintptr { return uintptr(p) } var swigDirectorTrack struct { sync.Mutex m map[int]interface{} c int } func swigDirectorAdd(v interface{}) int { swigDirectorTrack.Lock() defer swigDirectorTrack.Unlock() if swigDirectorTrack.m == nil { swigDirectorTrack.m = make(map[int]interface{}) } swigDirectorTrack.c++ ret := swigDirectorTrack.c swigDirectorTrack.m[ret] = v return ret } func swigDirectorLookup(c int) interface{} { swigDirectorTrack.Lock() defer swigDirectorTrack.Unlock() ret := swigDirectorTrack.m[c] if ret == nil { panic("C++ director pointer not found (possible use-after-free)") } return ret } func swigDirectorDelete(c int) { swigDirectorTrack.Lock() defer swigDirectorTrack.Unlock() if swigDirectorTrack.m[c] == nil { if c > swigDirectorTrack.c { panic("C++ director pointer invalid (possible memory corruption") } else { panic("C++ director pointer not found (possible use-after-free)") } } delete(swigDirectorTrack.m, c) } ================================================ FILE: pkg/gocv/cgo/swig/gocv/gocv.h ================================================ #ifndef GOCV_CGO_SWIG_GOCV_GOCV_H_ #define GOCV_CGO_SWIG_GOCV_GOCV_H_ #include #include #include namespace gocv { struct MagickInitializeMagickRequest { std::string path; }; struct MagickInitializeMagickResponse {}; struct MagickImageDecodeRequest { std::string image; std::string target_color_space; }; enum OrientationType { UndefinedOrientation = 0, TopLeftOrientation = 1, TopRightOrientation = 2, BottomRightOrientation = 3, BottomLeftOrientation = 4, LeftTopOrientation = 5, RightTopOrientation = 6, RightBottomOrientation = 7, LeftBottomOrientation = 8 }; // graphics-magick/include/magick/colorspace.h enum ColorspaceType { UndefinedColorspace = 0, RGBColorspace = 1, /* Plain old RGB colorspace */ GRAYColorspace = 2, /* Plain old full-range grayscale */ TransparentColorspace = 3, /* RGB but preserve matte channel during quantize */ OHTAColorspace = 4, XYZColorspace = 5, /* CIE XYZ */ YCCColorspace = 6, /* Kodak PhotoCD PhotoYCC */ YIQColorspace = 7, YPbPrColorspace = 8, YUVColorspace = 9, CMYKColorspace = 10, /* Cyan, magenta, yellow, black, alpha */ sRGBColorspace = 11, /* Kodak PhotoCD sRGB */ HSLColorspace = 12, /* Hue, saturation, luminosity */ HWBColorspace = 13, /* Hue, whiteness, blackness */ LABColorspace = 14, /* LAB colorspace not supported yet other than via lcms */ CineonLogRGBColorspace = 15, /* RGB data with Cineon Log scaling, 2.048 density range */ Rec601LumaColorspace = 16, /* Luma (Y) according to ITU-R 601 */ Rec601YCbCrColorspace = 17, /* YCbCr according to ITU-R 601 */ Rec709LumaColorspace = 18, /* Luma (Y) according to ITU-R 709 */ Rec709YCbCrColorspace = 19 /* YCbCr according to ITU-R 709 */ }; struct MagickImageDecodeResponse { cv::Mat mat; int rows; // height int columns; // width std::string magick; // File type magick identifier (.e.g "GIF") OrientationType orientation_type; ColorspaceType colorspace_type; }; #ifdef SWIG class MagicImage { #else class __attribute__((visibility("hidden"))) MagicImage { #endif public: MagicImage() = default; ~MagicImage(); static void MagickInitializeMagick(const MagickInitializeMagickRequest& req, MagickInitializeMagickResponse& resp); void MagickImageDecode(const MagickImageDecodeRequest& req, MagickImageDecodeResponse& resp); }; } // namespace gocv #endif ================================================ FILE: pkg/gocv/cgo/swig/gocv/gocv.swigcxx ================================================ //go:build ignore /* swig -go -cgo -c++ -intgosize 64 gocv.swigcxx */ %module(directors="1") gocv %include %include %include %include %include %{ #include "gocv.h" %} %exception { try { $action; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } %rename(Wrapped_MagicImage) MagicImage; %rename(Wrapped_MagickImageDecode) MagickImageDecode; %rename(Wrapped_Divide) Divide; /* %typemap(gotype) int "int32" %typemap(gotype) int64 "int64" %typemap(gotype) int64* "*int64" */ %header %{ %} %include "gocv.h" %go_import("fmt") %insert(go_wrapper) %{ type MagicImage interface { Wrapped_MagicImage MagickImageDecode(MagickImageDecodeRequest) (MagickImageDecodeResponse, error) } func NewMagicImage() MagicImage { mi := NewWrapped_MagicImage() return mi.(MagicImage) } // catch will recover from a panic and store the recover message to the error // parameter. The error must be passed by reference in order to be returned to the // calling function. func catch(err *error) { if r := recover(); r != nil { *err = fmt.Errorf("%v", r) } } func MagickInitializeMagick(req MagickInitializeMagickRequest) (resp MagickInitializeMagickResponse, err error) { defer catch(&err) resp = NewMagickInitializeMagickResponse() Wrapped_MagicImageMagickInitializeMagick(req, resp) return } func (arg SwigcptrWrapped_MagicImage) MagickImageDecode(req MagickImageDecodeRequest) (resp MagickImageDecodeResponse, err error) { defer catch(&err) resp = NewMagickImageDecodeResponse() arg.Wrapped_MagickImageDecode(req, resp) return } %} ================================================ FILE: pkg/gocv/cgo/swig/gocv/gocv_linux_amd64.cpp ================================================ #include #include #include "gocv.h" namespace gocv { MagicImage::~MagicImage() {} void MagicImage::MagickInitializeMagick( const MagickInitializeMagickRequest& req, MagickInitializeMagickResponse& resp) { if (req.path.empty()) { Magick::InitializeMagick(nullptr); return; } Magick::InitializeMagick(req.path.c_str()); } void MagicImage::MagickImageDecode(const MagickImageDecodeRequest& req, MagickImageDecodeResponse& resp) { if (req.image.empty()) { throw std::invalid_argument("image is empty"); } Magick::Image image; try { Magick::Blob blob((void*)(req.image.data()), req.image.length()); image.read(blob); } catch (Magick::Warning& w) { std::cout << "warn: " << w.what() << std::endl; // ignore warn } catch (Magick::Error& e) { std::cout << "a Magick++ error occurred: " << e.what() << std::endl; throw; } catch (...) { std::cout << "an unhandled error has occurred" << std::endl; throw; } int rows = image.rows(); int columns = image.columns(); if (rows <= 0 || columns <= 0) { throw std::invalid_argument(std::string("invalid image resolution [") + std::to_string(columns) + std::string(" x ") + std::to_string(rows) + std::string("]")); } cv::Mat mat; std::string map = req.target_color_space; do { image.colorSpace(Magick::RGBColorspace); if (map == "BGR") { mat = ::cv::Mat(rows, columns, CV_8UC3); image.write(0, 0, columns, rows, "BGR", Magick::CharPixel, mat.data); break; } if (map == "BGRA") { mat = ::cv::Mat(rows, columns, CV_8UC4); image.write(0, 0, columns, rows, "BGRA", Magick::CharPixel, mat.data); break; } if (map == "GRAY") { image.type(Magick::GrayscaleType); mat = ::cv::Mat(rows, columns, CV_8UC3); image.write(0, 0, columns, rows, "BGR", Magick::CharPixel, mat.data); break; } if (map == "GRAYA") { image.type(Magick::GrayscaleMatteType); mat = ::cv::Mat(rows, columns, CV_8UC4); image.write(0, 0, columns, rows, "BGRA", Magick::CharPixel, mat.data); break; } mat = ::cv::Mat(rows, columns, CV_8UC4); image.write(0, 0, columns, rows, map, Magick::CharPixel, mat.data); } while (false); resp.mat = mat.clone(); resp.magick = image.magick(); resp.orientation_type = static_cast(image.orientation()); resp.colorspace_type = static_cast(image.colorSpace()); resp.rows = rows; resp.columns = columns; return; } } // namespace gocv ================================================ FILE: pkg/gocv/cgo/swig/gocv/gocv_linux_amd64.go ================================================ package gocv ================================================ FILE: pkg/gocv/cgo/swig/gocv/gocv_test.go ================================================ package gocv_test import ( "testing" io_ "github.com/kaydxh/golang/go/io" gocv_ "github.com/kaydxh/golang/pkg/gocv/cgo/swig/gocv" ) func TestMagickInitializeMagick(t *testing.T) { } func TestMagickImageDecode(t *testing.T) { filename := "testdata/test.jpg" data, err := io_.ReadFile(filename) if err != nil { t.Error("Invalid ReadFile in TestMagickImageDecode") return } t.Logf("data size: %v", len(data)) sdk := gocv_.NewMagicImage() initReq := gocv_.NewMagickInitializeMagickRequest() _, err = gocv_.MagickInitializeMagick(initReq) if err != nil { t.Error(err.Error()) return } req := gocv_.NewMagickImageDecodeRequest() req.SetImage(string(data)) resp, err := sdk.MagickImageDecode(req) if err != nil { t.Error(err.Error()) return } t.Logf("resp row: %d, colunms: %v, magick: %v", resp.GetRows(), resp.GetColumns(), resp.GetMagick()) } ================================================ FILE: pkg/gocv/cgo/swig/gocv/gocv_wrap.cxx ================================================ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (https://www.swig.org). * Version 4.1.1 * * Do not make changes to this file unless you know what you are doing - modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ // source: gocv.swigcxx extern #ifdef __cplusplus "C" #endif void cgo_panic__gocv_ba346308b44e7b91(const char*); static void _swig_gopanic(const char *p) { cgo_panic__gocv_ba346308b44e7b91(p); } #define SWIG_VERSION 0x040101 #define SWIGGO #define SWIGMODULE gocv #define SWIG_DIRECTORS /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if defined(__GNUC__) # if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif /* Deal with Apple's deprecated 'AssertMacros.h' from Carbon-framework */ #if defined(__APPLE__) && !defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES) # define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0 #endif /* Intel's compiler complains if a variable which was never initialised is * cast to void, which is a common idiom which we use to indicate that we * are aware a variable isn't used. So we just silence that warning. * See: https://github.com/swig/swig/issues/192 for more discussion. */ #ifdef __INTEL_COMPILER # pragma warning disable 592 #endif #include #include #include #include #include typedef long long intgo; typedef unsigned long long uintgo; # if !defined(__clang__) && (defined(__i386__) || defined(__x86_64__)) # define SWIGSTRUCTPACKED __attribute__((__packed__, __gcc_struct__)) # else # define SWIGSTRUCTPACKED __attribute__((__packed__)) # endif typedef struct { char *p; intgo n; } _gostring_; typedef struct { void* array; intgo len; intgo cap; } _goslice_; #define SWIG_exception(code, msg) _swig_gopanic(msg) static _gostring_ Swig_AllocateString(const char *p, size_t l) { _gostring_ ret; ret.p = (char*)malloc(l); memcpy(ret.p, p, l); ret.n = l; return ret; } /* ----------------------------------------------------------------------------- * director_common.swg * * This file contains support for director classes which is common between * languages. * ----------------------------------------------------------------------------- */ /* Use -DSWIG_DIRECTOR_STATIC if you prefer to avoid the use of the 'Swig' namespace. This could be useful for multi-modules projects. */ #ifdef SWIG_DIRECTOR_STATIC /* Force anonymous (static) namespace */ #define Swig #endif /* ----------------------------------------------------------------------------- * director.swg * * This file contains support for director classes so that Go proxy * methods can be called from C++. * ----------------------------------------------------------------------------- */ #include #include namespace Swig { class DirectorException : public std::exception { }; } /* Handle memory management for directors. */ namespace { struct GCItem { virtual ~GCItem() {} }; struct GCItem_var { GCItem_var(GCItem *item = 0) : _item(item) { } GCItem_var& operator=(GCItem *item) { GCItem *tmp = _item; _item = item; delete tmp; return *this; } ~GCItem_var() { delete _item; } GCItem* operator->() { return _item; } private: GCItem *_item; }; template struct GCItem_T : GCItem { GCItem_T(Type *ptr) : _ptr(ptr) { } virtual ~GCItem_T() { delete _ptr; } private: Type *_ptr; }; } class Swig_memory { public: template void swig_acquire_pointer(Type* vptr) { if (vptr) { swig_owner[vptr] = new GCItem_T(vptr); } } private: typedef std::map swig_ownership_map; swig_ownership_map swig_owner; }; template static void swig_acquire_pointer(Swig_memory** pmem, Type* ptr) { if (!pmem) { *pmem = new Swig_memory; } (*pmem)->swig_acquire_pointer(ptr); } #ifdef __cplusplus #include /* SwigValueWrapper is described in swig.swg */ template class SwigValueWrapper { struct SwigSmartPointer { T *ptr; SwigSmartPointer(T *p) : ptr(p) { } ~SwigSmartPointer() { delete ptr; } SwigSmartPointer& operator=(SwigSmartPointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } void reset(T *p) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = p; } } pointer; SwigValueWrapper& operator=(const SwigValueWrapper& rhs); SwigValueWrapper(const SwigValueWrapper& rhs); public: SwigValueWrapper() : pointer(0) { } SwigValueWrapper& operator=(const T& t) { SwigSmartPointer tmp(new T(t)); pointer = tmp; return *this; } #if __cplusplus >=201103L SwigValueWrapper& operator=(T&& t) { SwigSmartPointer tmp(new T(std::move(t))); pointer = tmp; return *this; } operator T&&() const { return std::move(*pointer.ptr); } #else operator T&() const { return *pointer.ptr; } #endif T *operator&() const { return pointer.ptr; } static void reset(SwigValueWrapper& t, T *p) { t.pointer.reset(p); } }; /* * SwigValueInit() is a generic initialisation solution as the following approach: * * T c_result = T(); * * doesn't compile for all types for example: * * unsigned int c_result = unsigned int(); */ template T SwigValueInit() { return T(); } #if __cplusplus >=201103L # define SWIG_STD_MOVE(OBJ) std::move(OBJ) #else # define SWIG_STD_MOVE(OBJ) OBJ #endif #endif static void Swig_free(void* p) { free(p); } static void* Swig_malloc(int c) { return malloc(c); } #include #include #include #include #include #include #include #include #include "gocv.h" // C++ director class methods. #include "gocv_wrap.h" #ifdef __cplusplus extern "C" { #endif void _wrap_Swig_free_gocv_ba346308b44e7b91(void *_swig_go_0) { void *arg1 = (void *) 0 ; arg1 = *(void **)&_swig_go_0; Swig_free(arg1); } void *_wrap_Swig_malloc_gocv_ba346308b44e7b91(intgo _swig_go_0) { int arg1 ; void *result = 0 ; void *_swig_go_result; arg1 = (int)_swig_go_0; result = (void *)Swig_malloc(arg1); *(void **)&_swig_go_result = (void *)result; return _swig_go_result; } void _wrap_MagickInitializeMagickRequest_path_set_gocv_ba346308b44e7b91(gocv::MagickInitializeMagickRequest *_swig_go_0, _gostring_ _swig_go_1) { gocv::MagickInitializeMagickRequest *arg1 = (gocv::MagickInitializeMagickRequest *) 0 ; std::string *arg2 = 0 ; arg1 = *(gocv::MagickInitializeMagickRequest **)&_swig_go_0; std::string arg2_str(_swig_go_1.p, _swig_go_1.n); arg2 = &arg2_str; if (arg1) (arg1)->path = *arg2; } _gostring_ _wrap_MagickInitializeMagickRequest_path_get_gocv_ba346308b44e7b91(gocv::MagickInitializeMagickRequest *_swig_go_0) { gocv::MagickInitializeMagickRequest *arg1 = (gocv::MagickInitializeMagickRequest *) 0 ; std::string *result = 0 ; _gostring_ _swig_go_result; arg1 = *(gocv::MagickInitializeMagickRequest **)&_swig_go_0; result = (std::string *) & ((arg1)->path); _swig_go_result = Swig_AllocateString((*result).data(), (*result).length()); return _swig_go_result; } gocv::MagickInitializeMagickRequest *_wrap_new_MagickInitializeMagickRequest_gocv_ba346308b44e7b91() { gocv::MagickInitializeMagickRequest *result = 0 ; gocv::MagickInitializeMagickRequest *_swig_go_result; { try { result = (gocv::MagickInitializeMagickRequest *)new gocv::MagickInitializeMagickRequest();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(gocv::MagickInitializeMagickRequest **)&_swig_go_result = (gocv::MagickInitializeMagickRequest *)result; return _swig_go_result; } void _wrap_delete_MagickInitializeMagickRequest_gocv_ba346308b44e7b91(gocv::MagickInitializeMagickRequest *_swig_go_0) { gocv::MagickInitializeMagickRequest *arg1 = (gocv::MagickInitializeMagickRequest *) 0 ; arg1 = *(gocv::MagickInitializeMagickRequest **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } gocv::MagickInitializeMagickResponse *_wrap_new_MagickInitializeMagickResponse_gocv_ba346308b44e7b91() { gocv::MagickInitializeMagickResponse *result = 0 ; gocv::MagickInitializeMagickResponse *_swig_go_result; { try { result = (gocv::MagickInitializeMagickResponse *)new gocv::MagickInitializeMagickResponse();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(gocv::MagickInitializeMagickResponse **)&_swig_go_result = (gocv::MagickInitializeMagickResponse *)result; return _swig_go_result; } void _wrap_delete_MagickInitializeMagickResponse_gocv_ba346308b44e7b91(gocv::MagickInitializeMagickResponse *_swig_go_0) { gocv::MagickInitializeMagickResponse *arg1 = (gocv::MagickInitializeMagickResponse *) 0 ; arg1 = *(gocv::MagickInitializeMagickResponse **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } void _wrap_MagickImageDecodeRequest_image_set_gocv_ba346308b44e7b91(gocv::MagickImageDecodeRequest *_swig_go_0, _gostring_ _swig_go_1) { gocv::MagickImageDecodeRequest *arg1 = (gocv::MagickImageDecodeRequest *) 0 ; std::string *arg2 = 0 ; arg1 = *(gocv::MagickImageDecodeRequest **)&_swig_go_0; std::string arg2_str(_swig_go_1.p, _swig_go_1.n); arg2 = &arg2_str; if (arg1) (arg1)->image = *arg2; } _gostring_ _wrap_MagickImageDecodeRequest_image_get_gocv_ba346308b44e7b91(gocv::MagickImageDecodeRequest *_swig_go_0) { gocv::MagickImageDecodeRequest *arg1 = (gocv::MagickImageDecodeRequest *) 0 ; std::string *result = 0 ; _gostring_ _swig_go_result; arg1 = *(gocv::MagickImageDecodeRequest **)&_swig_go_0; result = (std::string *) & ((arg1)->image); _swig_go_result = Swig_AllocateString((*result).data(), (*result).length()); return _swig_go_result; } void _wrap_MagickImageDecodeRequest_target_color_space_set_gocv_ba346308b44e7b91(gocv::MagickImageDecodeRequest *_swig_go_0, _gostring_ _swig_go_1) { gocv::MagickImageDecodeRequest *arg1 = (gocv::MagickImageDecodeRequest *) 0 ; std::string *arg2 = 0 ; arg1 = *(gocv::MagickImageDecodeRequest **)&_swig_go_0; std::string arg2_str(_swig_go_1.p, _swig_go_1.n); arg2 = &arg2_str; if (arg1) (arg1)->target_color_space = *arg2; } _gostring_ _wrap_MagickImageDecodeRequest_target_color_space_get_gocv_ba346308b44e7b91(gocv::MagickImageDecodeRequest *_swig_go_0) { gocv::MagickImageDecodeRequest *arg1 = (gocv::MagickImageDecodeRequest *) 0 ; std::string *result = 0 ; _gostring_ _swig_go_result; arg1 = *(gocv::MagickImageDecodeRequest **)&_swig_go_0; result = (std::string *) & ((arg1)->target_color_space); _swig_go_result = Swig_AllocateString((*result).data(), (*result).length()); return _swig_go_result; } gocv::MagickImageDecodeRequest *_wrap_new_MagickImageDecodeRequest_gocv_ba346308b44e7b91() { gocv::MagickImageDecodeRequest *result = 0 ; gocv::MagickImageDecodeRequest *_swig_go_result; { try { result = (gocv::MagickImageDecodeRequest *)new gocv::MagickImageDecodeRequest();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(gocv::MagickImageDecodeRequest **)&_swig_go_result = (gocv::MagickImageDecodeRequest *)result; return _swig_go_result; } void _wrap_delete_MagickImageDecodeRequest_gocv_ba346308b44e7b91(gocv::MagickImageDecodeRequest *_swig_go_0) { gocv::MagickImageDecodeRequest *arg1 = (gocv::MagickImageDecodeRequest *) 0 ; arg1 = *(gocv::MagickImageDecodeRequest **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } intgo _wrap_UndefinedOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::UndefinedOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_TopLeftOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::TopLeftOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_TopRightOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::TopRightOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_BottomRightOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::BottomRightOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_BottomLeftOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::BottomLeftOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_LeftTopOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::LeftTopOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_RightTopOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::RightTopOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_RightBottomOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::RightBottomOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_LeftBottomOrientation_gocv_ba346308b44e7b91() { gocv::OrientationType result; intgo _swig_go_result; { try { result = gocv::LeftBottomOrientation; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_UndefinedColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::UndefinedColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_RGBColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::RGBColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_GRAYColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::GRAYColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_TransparentColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::TransparentColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_OHTAColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::OHTAColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_XYZColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::XYZColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_YCCColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::YCCColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_YIQColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::YIQColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_YPbPrColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::YPbPrColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_YUVColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::YUVColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_CMYKColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::CMYKColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_sRGBColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::sRGBColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_HSLColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::HSLColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_HWBColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::HWBColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_LABColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::LABColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_CineonLogRGBColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::CineonLogRGBColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_Rec601LumaColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::Rec601LumaColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_Rec601YCbCrColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::Rec601YCbCrColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_Rec709LumaColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::Rec709LumaColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } intgo _wrap_Rec709YCbCrColorspace_gocv_ba346308b44e7b91() { gocv::ColorspaceType result; intgo _swig_go_result; { try { result = gocv::Rec709YCbCrColorspace; ; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } _swig_go_result = (intgo)result; return _swig_go_result; } void _wrap_MagickImageDecodeResponse_mat_set_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0, cv::Mat *_swig_go_1) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; cv::Mat arg2 ; cv::Mat *argp2 ; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; argp2 = (cv::Mat *)_swig_go_1; if (argp2 == NULL) { _swig_gopanic("Attempt to dereference null cv::Mat"); } arg2 = (cv::Mat)*argp2; if (arg1) (arg1)->mat = arg2; } cv::Mat *_wrap_MagickImageDecodeResponse_mat_get_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; cv::Mat result; cv::Mat *_swig_go_result; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; result = ((arg1)->mat); *(cv::Mat **)&_swig_go_result = new cv::Mat(result); return _swig_go_result; } void _wrap_MagickImageDecodeResponse_rows_set_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0, intgo _swig_go_1) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; int arg2 ; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; arg2 = (int)_swig_go_1; if (arg1) (arg1)->rows = arg2; } intgo _wrap_MagickImageDecodeResponse_rows_get_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; int result; intgo _swig_go_result; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; result = (int) ((arg1)->rows); _swig_go_result = result; return _swig_go_result; } void _wrap_MagickImageDecodeResponse_columns_set_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0, intgo _swig_go_1) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; int arg2 ; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; arg2 = (int)_swig_go_1; if (arg1) (arg1)->columns = arg2; } intgo _wrap_MagickImageDecodeResponse_columns_get_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; int result; intgo _swig_go_result; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; result = (int) ((arg1)->columns); _swig_go_result = result; return _swig_go_result; } void _wrap_MagickImageDecodeResponse_magick_set_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0, _gostring_ _swig_go_1) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; std::string *arg2 = 0 ; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; std::string arg2_str(_swig_go_1.p, _swig_go_1.n); arg2 = &arg2_str; if (arg1) (arg1)->magick = *arg2; } _gostring_ _wrap_MagickImageDecodeResponse_magick_get_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; std::string *result = 0 ; _gostring_ _swig_go_result; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; result = (std::string *) & ((arg1)->magick); _swig_go_result = Swig_AllocateString((*result).data(), (*result).length()); return _swig_go_result; } void _wrap_MagickImageDecodeResponse_orientation_type_set_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0, intgo _swig_go_1) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; gocv::OrientationType arg2 ; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; arg2 = (gocv::OrientationType)_swig_go_1; if (arg1) (arg1)->orientation_type = arg2; } intgo _wrap_MagickImageDecodeResponse_orientation_type_get_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; gocv::OrientationType result; intgo _swig_go_result; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; result = (gocv::OrientationType) ((arg1)->orientation_type); _swig_go_result = (intgo)result; return _swig_go_result; } void _wrap_MagickImageDecodeResponse_colorspace_type_set_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0, intgo _swig_go_1) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; gocv::ColorspaceType arg2 ; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; arg2 = (gocv::ColorspaceType)_swig_go_1; if (arg1) (arg1)->colorspace_type = arg2; } intgo _wrap_MagickImageDecodeResponse_colorspace_type_get_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; gocv::ColorspaceType result; intgo _swig_go_result; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; result = (gocv::ColorspaceType) ((arg1)->colorspace_type); _swig_go_result = (intgo)result; return _swig_go_result; } gocv::MagickImageDecodeResponse *_wrap_new_MagickImageDecodeResponse_gocv_ba346308b44e7b91() { gocv::MagickImageDecodeResponse *result = 0 ; gocv::MagickImageDecodeResponse *_swig_go_result; { try { result = (gocv::MagickImageDecodeResponse *)new gocv::MagickImageDecodeResponse();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(gocv::MagickImageDecodeResponse **)&_swig_go_result = (gocv::MagickImageDecodeResponse *)result; return _swig_go_result; } void _wrap_delete_MagickImageDecodeResponse_gocv_ba346308b44e7b91(gocv::MagickImageDecodeResponse *_swig_go_0) { gocv::MagickImageDecodeResponse *arg1 = (gocv::MagickImageDecodeResponse *) 0 ; arg1 = *(gocv::MagickImageDecodeResponse **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } gocv::MagicImage *_wrap_new_Wrapped_MagicImage_gocv_ba346308b44e7b91() { gocv::MagicImage *result = 0 ; gocv::MagicImage *_swig_go_result; { try { result = (gocv::MagicImage *)new gocv::MagicImage();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(gocv::MagicImage **)&_swig_go_result = (gocv::MagicImage *)result; return _swig_go_result; } void _wrap_delete_Wrapped_MagicImage_gocv_ba346308b44e7b91(gocv::MagicImage *_swig_go_0) { gocv::MagicImage *arg1 = (gocv::MagicImage *) 0 ; arg1 = *(gocv::MagicImage **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } void _wrap_Wrapped_MagicImage_MagickInitializeMagick_gocv_ba346308b44e7b91(gocv::MagickInitializeMagickRequest *_swig_go_0, gocv::MagickInitializeMagickResponse *_swig_go_1) { gocv::MagickInitializeMagickRequest *arg1 = 0 ; gocv::MagickInitializeMagickResponse *arg2 = 0 ; arg1 = *(gocv::MagickInitializeMagickRequest **)&_swig_go_0; arg2 = *(gocv::MagickInitializeMagickResponse **)&_swig_go_1; { try { gocv::MagicImage::MagickInitializeMagick((gocv::MagickInitializeMagickRequest const &)*arg1,*arg2);; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } void _wrap_Wrapped_MagicImage_Wrapped_MagickImageDecode_gocv_ba346308b44e7b91(gocv::MagicImage *_swig_go_0, gocv::MagickImageDecodeRequest *_swig_go_1, gocv::MagickImageDecodeResponse *_swig_go_2) { gocv::MagicImage *arg1 = (gocv::MagicImage *) 0 ; gocv::MagickImageDecodeRequest *arg2 = 0 ; gocv::MagickImageDecodeResponse *arg3 = 0 ; arg1 = *(gocv::MagicImage **)&_swig_go_0; arg2 = *(gocv::MagickImageDecodeRequest **)&_swig_go_1; arg3 = *(gocv::MagickImageDecodeResponse **)&_swig_go_2; { try { (arg1)->MagickImageDecode((gocv::MagickImageDecodeRequest const &)*arg2,*arg3);; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } #ifdef __cplusplus } #endif ================================================ FILE: pkg/gocv/cgo/swig/gocv/gocv_wrap.h ================================================ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (https://www.swig.org). * Version 4.1.1 * * Do not make changes to this file unless you know what you are doing - modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ // source: gocv.swigcxx #ifndef SWIG_gocv_WRAP_H_ #define SWIG_gocv_WRAP_H_ class Swig_memory; #endif ================================================ FILE: pkg/gocv/cgo/swig/pycv/Makefile ================================================ MAKEFILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) PROJECT_ROOT_DIR := $(realpath ${MAKEFILE_DIR}/../..) PKG_CONFIG_PATH := ${PROJECT_ROOT_DIR}/pkgconfig SCRIPT_PATH := ${MAKEFILE_DIR}/../../script TARGET := $(shell basename ${MAKEFILE_DIR}) # https://web.mit.edu/gnu/doc/html/make_8.html _empty:= # define space with $(_empty) _space:= $(_empty) $(_empty) define joinwith $(subst $(_space),$1,$(strip $2)) endef .PHONY: all all: deps generate test @echo "${MAKEFILE_DIR}" @echo "${PROJECT_ROOT_DIR}" @echo "${TARGET}" .PHONY: deps deps: @echo " > downloading deps library" .PHONY: version version: @bash -c "bash ${SCRIPT_PATH}/version.sh gitinfos" .PHONY: test test: version @$(eval THIRD_LIB_PATHS := $(shell find -L ${PROJECT_ROOT_DIR}/third_path/ -type d -iname "lib*" -print0 |xargs -0 -I {} bash -c 'echo {}'|grep -v "stubs")) @echo ${THIRD_LIB_PATHS} @$(eval JOINED_THIRD_LIB_PATHS := $(call joinwith,:,$(THIRD_LIB_PATHS))) PKG_CONFIG_PATH="${PKG_CONFIG_PATH}" LD_LIBRARY_PATH="$(JOINED_THIRD_LIB_PATHS):${LD_LIBRARY_PATH}" LIBRARY_PATH="$(JOINED_THIRD_LIB_PATHS):${LIBRARY_PATH}" go test -a -v . .PHONY: generate generate: ================================================ FILE: pkg/gocv/cgo/swig/pycv/__init__.py ================================================ ================================================ FILE: pkg/gocv/cgo/swig/pycv/cgo.go ================================================ package pycv /* #cgo linux,amd64 pkg-config: pybind11 #cgo !linux !amd64 CXXFLAGS: -D__CGO_UNKNOWN_PLATFORM__ #cgo CXXFLAGS: -std=c++11 #include */ import "C" ================================================ FILE: pkg/gocv/cgo/swig/pycv/pycv.go ================================================ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (https://www.swig.org). * Version 4.1.1 * * Do not make changes to this file unless you know what you are doing - modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ // source: pycv.swigcxx package pycv /* #define intgo swig_intgo typedef void *swig_voidp; #include #include typedef long long intgo; typedef unsigned long long uintgo; typedef struct { char *p; intgo n; } _gostring_; typedef struct { void* array; intgo len; intgo cap; } _goslice_; typedef _gostring_ swig_type_1; typedef _gostring_ swig_type_2; typedef _gostring_ swig_type_3; typedef _gostring_ swig_type_4; typedef _gostring_ swig_type_5; typedef _gostring_ swig_type_6; typedef _gostring_ swig_type_7; typedef _gostring_ swig_type_8; typedef _gostring_ swig_type_9; extern void _wrap_Swig_free_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern uintptr_t _wrap_Swig_malloc_pycv_ffa8ea6aa3be9035(swig_intgo arg1); extern void _wrap_LocalInitRequest_gpu_id_set_pycv_ffa8ea6aa3be9035(uintptr_t arg1, swig_intgo arg2); extern swig_intgo _wrap_LocalInitRequest_gpu_id_get_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern void _wrap_LocalInitRequest_sdk_dir_set_pycv_ffa8ea6aa3be9035(uintptr_t arg1, swig_type_1 arg2); extern swig_type_2 _wrap_LocalInitRequest_sdk_dir_get_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern void _wrap_LocalInitRequest_model_dir_set_pycv_ffa8ea6aa3be9035(uintptr_t arg1, swig_type_3 arg2); extern swig_type_4 _wrap_LocalInitRequest_model_dir_get_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern uintptr_t _wrap_new_LocalInitRequest_pycv_ffa8ea6aa3be9035(void); extern void _wrap_delete_LocalInitRequest_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern uintptr_t _wrap_new_LocalInitResponse_pycv_ffa8ea6aa3be9035(void); extern void _wrap_delete_LocalInitResponse_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern void _wrap_DoRequest_arg1_set_pycv_ffa8ea6aa3be9035(uintptr_t arg1, swig_type_5 arg2); extern swig_type_6 _wrap_DoRequest_arg1_get_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern void _wrap_DoRequest_arg2_set_pycv_ffa8ea6aa3be9035(uintptr_t arg1, swig_type_7 arg2); extern swig_type_8 _wrap_DoRequest_arg2_get_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern uintptr_t _wrap_new_DoRequest_pycv_ffa8ea6aa3be9035(void); extern void _wrap_delete_DoRequest_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern uintptr_t _wrap_new_DoResponse_pycv_ffa8ea6aa3be9035(void); extern void _wrap_delete_DoResponse_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern uintptr_t _wrap_new_Wrapped_PyImage_pycv_ffa8ea6aa3be9035(void); extern void _wrap_delete_Wrapped_PyImage_pycv_ffa8ea6aa3be9035(uintptr_t arg1); extern void _wrap_Wrapped_PyImage_GlobalInit_pycv_ffa8ea6aa3be9035(swig_type_9 arg1, swig_intgo arg2); extern void _wrap_Wrapped_PyImage_GlobalRelease_pycv_ffa8ea6aa3be9035(void); extern void _wrap_Wrapped_PyImage_Wrapped_PyImage_LocalInit_pycv_ffa8ea6aa3be9035(uintptr_t arg1, uintptr_t arg2, uintptr_t arg3); extern void _wrap_Wrapped_PyImage_Wrapped_PyImage_Do_pycv_ffa8ea6aa3be9035(uintptr_t arg1, uintptr_t arg2, uintptr_t arg3); #undef intgo */ import "C" import "unsafe" import _ "runtime/cgo" import "sync" import "fmt" type _ unsafe.Pointer var Swig_escape_always_false bool var Swig_escape_val interface{} type _swig_fnptr *byte type _swig_memberptr *byte func getSwigcptr(v interface { Swigcptr() uintptr }) uintptr { if v == nil { return 0 } return v.Swigcptr() } type _ sync.Mutex //export cgo_panic__pycv_ffa8ea6aa3be9035 func cgo_panic__pycv_ffa8ea6aa3be9035(p *byte) { s := (*[1024]byte)(unsafe.Pointer(p))[:] for i, b := range s { if b == 0 { panic(string(s[:i])) } } panic(string(s)) } type swig_gostring struct { p uintptr; n int } func swigCopyString(s string) string { p := *(*swig_gostring)(unsafe.Pointer(&s)) r := string((*[0x7fffffff]byte)(unsafe.Pointer(p.p))[:p.n]) Swig_free(p.p) return r } func Swig_free(arg1 uintptr) { _swig_i_0 := arg1 C._wrap_Swig_free_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) } func Swig_malloc(arg1 int) (_swig_ret uintptr) { var swig_r uintptr _swig_i_0 := arg1 swig_r = (uintptr)(C._wrap_Swig_malloc_pycv_ffa8ea6aa3be9035(C.swig_intgo(_swig_i_0))) return swig_r } type SwigcptrLocalInitRequest uintptr func (p SwigcptrLocalInitRequest) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrLocalInitRequest) SwigIsLocalInitRequest() { } func (arg1 SwigcptrLocalInitRequest) SetGpu_id(arg2 int) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_LocalInitRequest_gpu_id_set_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0), C.swig_intgo(_swig_i_1)) } func (arg1 SwigcptrLocalInitRequest) GetGpu_id() (_swig_ret int) { var swig_r int _swig_i_0 := arg1 swig_r = (int)(C._wrap_LocalInitRequest_gpu_id_get_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0))) return swig_r } func (arg1 SwigcptrLocalInitRequest) SetSdk_dir(arg2 string) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_LocalInitRequest_sdk_dir_set_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0), *(*C.swig_type_1)(unsafe.Pointer(&_swig_i_1))) if Swig_escape_always_false { Swig_escape_val = arg2 } } func (arg1 SwigcptrLocalInitRequest) GetSdk_dir() (_swig_ret string) { var swig_r string _swig_i_0 := arg1 swig_r_p := C._wrap_LocalInitRequest_sdk_dir_get_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) swig_r = *(*string)(unsafe.Pointer(&swig_r_p)) var swig_r_1 string swig_r_1 = swigCopyString(swig_r) return swig_r_1 } func (arg1 SwigcptrLocalInitRequest) SetModel_dir(arg2 string) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_LocalInitRequest_model_dir_set_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0), *(*C.swig_type_3)(unsafe.Pointer(&_swig_i_1))) if Swig_escape_always_false { Swig_escape_val = arg2 } } func (arg1 SwigcptrLocalInitRequest) GetModel_dir() (_swig_ret string) { var swig_r string _swig_i_0 := arg1 swig_r_p := C._wrap_LocalInitRequest_model_dir_get_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) swig_r = *(*string)(unsafe.Pointer(&swig_r_p)) var swig_r_1 string swig_r_1 = swigCopyString(swig_r) return swig_r_1 } func NewLocalInitRequest() (_swig_ret LocalInitRequest) { var swig_r LocalInitRequest swig_r = (LocalInitRequest)(SwigcptrLocalInitRequest(C._wrap_new_LocalInitRequest_pycv_ffa8ea6aa3be9035())) return swig_r } func DeleteLocalInitRequest(arg1 LocalInitRequest) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_LocalInitRequest_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) } type LocalInitRequest interface { Swigcptr() uintptr SwigIsLocalInitRequest() SetGpu_id(arg2 int) GetGpu_id() (_swig_ret int) SetSdk_dir(arg2 string) GetSdk_dir() (_swig_ret string) SetModel_dir(arg2 string) GetModel_dir() (_swig_ret string) } type SwigcptrLocalInitResponse uintptr func (p SwigcptrLocalInitResponse) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrLocalInitResponse) SwigIsLocalInitResponse() { } func NewLocalInitResponse() (_swig_ret LocalInitResponse) { var swig_r LocalInitResponse swig_r = (LocalInitResponse)(SwigcptrLocalInitResponse(C._wrap_new_LocalInitResponse_pycv_ffa8ea6aa3be9035())) return swig_r } func DeleteLocalInitResponse(arg1 LocalInitResponse) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_LocalInitResponse_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) } type LocalInitResponse interface { Swigcptr() uintptr SwigIsLocalInitResponse() } type SwigcptrDoRequest uintptr func (p SwigcptrDoRequest) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrDoRequest) SwigIsDoRequest() { } func (arg1 SwigcptrDoRequest) SetArg1(arg2 string) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_DoRequest_arg1_set_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0), *(*C.swig_type_5)(unsafe.Pointer(&_swig_i_1))) if Swig_escape_always_false { Swig_escape_val = arg2 } } func (arg1 SwigcptrDoRequest) GetArg1() (_swig_ret string) { var swig_r string _swig_i_0 := arg1 swig_r_p := C._wrap_DoRequest_arg1_get_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) swig_r = *(*string)(unsafe.Pointer(&swig_r_p)) var swig_r_1 string swig_r_1 = swigCopyString(swig_r) return swig_r_1 } func (arg1 SwigcptrDoRequest) SetArg2(arg2 string) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_DoRequest_arg2_set_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0), *(*C.swig_type_7)(unsafe.Pointer(&_swig_i_1))) if Swig_escape_always_false { Swig_escape_val = arg2 } } func (arg1 SwigcptrDoRequest) GetArg2() (_swig_ret string) { var swig_r string _swig_i_0 := arg1 swig_r_p := C._wrap_DoRequest_arg2_get_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) swig_r = *(*string)(unsafe.Pointer(&swig_r_p)) var swig_r_1 string swig_r_1 = swigCopyString(swig_r) return swig_r_1 } func NewDoRequest() (_swig_ret DoRequest) { var swig_r DoRequest swig_r = (DoRequest)(SwigcptrDoRequest(C._wrap_new_DoRequest_pycv_ffa8ea6aa3be9035())) return swig_r } func DeleteDoRequest(arg1 DoRequest) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_DoRequest_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) } type DoRequest interface { Swigcptr() uintptr SwigIsDoRequest() SetArg1(arg2 string) GetArg1() (_swig_ret string) SetArg2(arg2 string) GetArg2() (_swig_ret string) } type SwigcptrDoResponse uintptr func (p SwigcptrDoResponse) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrDoResponse) SwigIsDoResponse() { } func NewDoResponse() (_swig_ret DoResponse) { var swig_r DoResponse swig_r = (DoResponse)(SwigcptrDoResponse(C._wrap_new_DoResponse_pycv_ffa8ea6aa3be9035())) return swig_r } func DeleteDoResponse(arg1 DoResponse) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_DoResponse_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) } type DoResponse interface { Swigcptr() uintptr SwigIsDoResponse() } type SwigcptrWrapped_PyImage uintptr func (p SwigcptrWrapped_PyImage) Swigcptr() uintptr { return (uintptr)(p) } func (p SwigcptrWrapped_PyImage) SwigIsWrapped_PyImage() { } func NewWrapped_PyImage() (_swig_ret Wrapped_PyImage) { var swig_r Wrapped_PyImage swig_r = (Wrapped_PyImage)(SwigcptrWrapped_PyImage(C._wrap_new_Wrapped_PyImage_pycv_ffa8ea6aa3be9035())) return swig_r } func DeleteWrapped_PyImage(arg1 Wrapped_PyImage) { _swig_i_0 := getSwigcptr(arg1) C._wrap_delete_Wrapped_PyImage_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0)) } func Wrapped_PyImageGlobalInit(arg1 string, arg2 int) { _swig_i_0 := arg1 _swig_i_1 := arg2 C._wrap_Wrapped_PyImage_GlobalInit_pycv_ffa8ea6aa3be9035(*(*C.swig_type_9)(unsafe.Pointer(&_swig_i_0)), C.swig_intgo(_swig_i_1)) if Swig_escape_always_false { Swig_escape_val = arg1 } } func Wrapped_PyImageGlobalRelease() { C._wrap_Wrapped_PyImage_GlobalRelease_pycv_ffa8ea6aa3be9035() } func (arg1 SwigcptrWrapped_PyImage) Wrapped_PyImage_LocalInit(arg2 LocalInitRequest, arg3 LocalInitResponse) { _swig_i_0 := arg1 _swig_i_1 := getSwigcptr(arg2) _swig_i_2 := getSwigcptr(arg3) C._wrap_Wrapped_PyImage_Wrapped_PyImage_LocalInit_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0), C.uintptr_t(_swig_i_1), C.uintptr_t(_swig_i_2)) } func (arg1 SwigcptrWrapped_PyImage) Wrapped_PyImage_Do(arg2 DoRequest, arg3 DoResponse) { _swig_i_0 := arg1 _swig_i_1 := getSwigcptr(arg2) _swig_i_2 := getSwigcptr(arg3) C._wrap_Wrapped_PyImage_Wrapped_PyImage_Do_pycv_ffa8ea6aa3be9035(C.uintptr_t(_swig_i_0), C.uintptr_t(_swig_i_1), C.uintptr_t(_swig_i_2)) } type Wrapped_PyImage interface { Swigcptr() uintptr SwigIsWrapped_PyImage() Wrapped_PyImage_LocalInit(arg2 LocalInitRequest, arg3 LocalInitResponse) Wrapped_PyImage_Do(arg2 DoRequest, arg3 DoResponse) } type PyImage interface { Wrapped_PyImage LocalInit(LocalInitRequest) (LocalInitResponse, error); Do(DoRequest) (DoResponse, error); } func NewPyImage() PyImage { e := NewWrapped_PyImage() return e.(PyImage) } // catch will recover from a panic and store the recover message to the error // parameter. The error must be passed by reference in order to be returned to the // calling function. func catch(err *error) { if r := recover(); r != nil { *err = fmt.Errorf("%v", r) } } func GlobalInit(model_dir string, gpu_id int) (err error) { defer catch(&err) Wrapped_PyImageGlobalInit(model_dir, gpu_id) return } func GlobalRelease() (err error){ defer catch(&err) Wrapped_PyImageGlobalRelease() return } func (arg SwigcptrWrapped_PyImage) LocalInit(req LocalInitRequest) (resp LocalInitResponse, err error) { defer catch(&err) resp = NewLocalInitResponse() arg.Wrapped_PyImage_LocalInit(req, resp) return } func (arg SwigcptrWrapped_PyImage) Do(req DoRequest) (resp DoResponse, err error) { defer catch(&err) resp = NewDoResponse() arg.Wrapped_PyImage_Do(req, resp) return } var swigDirectorTrack struct { sync.Mutex m map[int]interface{} c int } func swigDirectorAdd(v interface{}) int { swigDirectorTrack.Lock() defer swigDirectorTrack.Unlock() if swigDirectorTrack.m == nil { swigDirectorTrack.m = make(map[int]interface{}) } swigDirectorTrack.c++ ret := swigDirectorTrack.c swigDirectorTrack.m[ret] = v return ret } func swigDirectorLookup(c int) interface{} { swigDirectorTrack.Lock() defer swigDirectorTrack.Unlock() ret := swigDirectorTrack.m[c] if ret == nil { panic("C++ director pointer not found (possible use-after-free)") } return ret } func swigDirectorDelete(c int) { swigDirectorTrack.Lock() defer swigDirectorTrack.Unlock() if swigDirectorTrack.m[c] == nil { if c > swigDirectorTrack.c { panic("C++ director pointer invalid (possible memory corruption") } else { panic("C++ director pointer not found (possible use-after-free)") } } delete(swigDirectorTrack.m, c) } ================================================ FILE: pkg/gocv/cgo/swig/pycv/pycv.h ================================================ #ifndef GOCV_CGO_SWIG_PYCV_PYCV_H_ #define GOCV_CGO_SWIG_PYCV_PYCV_H_ #include #include #include namespace pybind11 { class object; } namespace pycv { struct LocalInitRequest { int gpu_id = -1; std::string sdk_dir; std::string model_dir; }; struct LocalInitResponse {}; struct DoRequest { std::string arg1; std::string arg2; }; struct DoResponse {}; #ifdef SWIG class PyImage { #else class __attribute__((visibility("hidden"))) PyImage { #endif pybind11::object sdk_py; public: PyImage() = default; ~PyImage(); static void GlobalInit(const std::string& model_dir, int gpu_id); static void GlobalRelease(); void LocalInit(const LocalInitRequest& req, LocalInitResponse& resp); void Do(const DoRequest& req, DoResponse& resp); }; } // namespace pycv #endif ================================================ FILE: pkg/gocv/cgo/swig/pycv/pycv.py ================================================ import base64 import sys import traceback import copy from PIL import Image def read_image(image_file_path, base64_format=True): with open(image_file_path, "rb") as file: data = file.read() if not base64_format: return data base64_data = base64.b64encode(data) return base64_data def write_image(image_data, image_file_path, base64_format=True): if base64_format: data = base64.b64decode(image_data) else: data = image_data f = io.BytesIO(data) Image.open(f) os.makedirs(os.path.dirname(image_file), exist_ok=True) image.save(image_file_path) class CVSDK: def __init__(self, gpu_id: int = -1, **kwargs): self.gpu_id = -1 self.init_kwargs = {} self.sdk = None def init(self, model_dir: str, gpu_id: int = -1, **kwargs): try: if not self.sdk: del self.sdk self.sdk = None self.gpu_id = gpu_id self.init_kwargs = copy.copy(kwargs) if "sdk_dir" in kwargs: sdk_dir = kwargs.get("sdk_dir") del kwargs["sdk_dir"] if sdk_dir not in sys.path: sys.path.append(sdk_dir) # init sdk isinstance # self.sdk = None except ValueError as err: return { "err" : f"CVSDK::__init__: Unexpected ValueError {err=}, {type(err)=}, {traceback.format_exc()}", } except Exception as err: return { "err" : f"CVSDK::__init__: Unexpected Exception {err=}, {type(err)=}, {traceback.format_exc()}", } except: err = sys.exc_info()[0] return { "err" : f"CVSDK::__init__: Unexpected Exception {err=}, {type(err)=}, {traceback.format_exc()}", } return {} def do(self, **kwargs): try: arg1 = kwargs.get("arg1", "") arg2 = kwargs.get("arg2", "") #todo sdk call return { "result": "ok" } except ValueError as err: return { "err" : f"CVSDK::Do: Unexpected ValueError {err=}, {type(err)=}, {traceback.format_exc()}", } except Exception as err: return { "err" : f"CVSDK::Do: Unexpected Exception {err=}, {type(err)=}, {traceback.format_exc()}", } except: err = sys.exc_info()[0] return { "err" : f"CVSDK::Do: Unexpected Exception {err=}, {type(err)=}, {traceback.format_exc()}", } if __name__ == "__main__": print('sys.path %s' % sys.path) sdk = CVSDK() sdk.init("") resp = sdk.do() if 'err' in resp: err = resp['err'] print(f'do err: {err}') print(f'{resp["result"]}') ================================================ FILE: pkg/gocv/cgo/swig/pycv/pycv.swigcxx ================================================ //go:build ignore /* swig -go -cgo -c++ -intgosize 64 pycv.swigcxx */ %module(directors="1") pycv %include %include %include %include %include %{ #include "pycv.h" %} %exception { try { $action; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } %rename(Wrapped_PyImage) PyImage; %rename(Wrapped_PyImage_LocalInit) LocalInit; %rename(Wrapped_PyImage_Do) Do; %header %{ %} %include "pycv.h" %go_import("fmt") %insert(go_wrapper) %{ type PyImage interface { Wrapped_PyImage LocalInit(LocalInitRequest) (LocalInitResponse, error); Do(DoRequest) (DoResponse, error); } func NewPyImage() PyImage { e := NewWrapped_PyImage() return e.(PyImage) } // catch will recover from a panic and store the recover message to the error // parameter. The error must be passed by reference in order to be returned to the // calling function. func catch(err *error) { if r := recover(); r != nil { *err = fmt.Errorf("%v", r) } } func GlobalInit(model_dir string, gpu_id int) (err error) { defer catch(&err) Wrapped_PyImageGlobalInit(model_dir, gpu_id) return } func GlobalRelease() (err error){ defer catch(&err) Wrapped_PyImageGlobalRelease() return } func (arg SwigcptrWrapped_PyImage) LocalInit(req LocalInitRequest) (resp LocalInitResponse, err error) { defer catch(&err) resp = NewLocalInitResponse() arg.Wrapped_PyImage_LocalInit(req, resp) return } func (arg SwigcptrWrapped_PyImage) Do(req DoRequest) (resp DoResponse, err error) { defer catch(&err) resp = NewDoResponse() arg.Wrapped_PyImage_Do(req, resp) return } %} ================================================ FILE: pkg/gocv/cgo/swig/pycv/pycv_linux_amd64.cpp ================================================ #include #include #include #include #include #include "pycv.h" namespace py = pybind11; using namespace pybind11::literals; // to bring in the `_a` literal #ifdef __cplusplus #define UIKIT_EXTERN extern "C" __attribute__((visibility("default"))) #else #define UIKIT_EXTERN extern __attribute__((visibility("default"))) #endif static std::once_flag python_once; static std::unique_ptr python_interpreter_guard; static std::unique_ptr python_interpreter_gil_scoped_release; pycv::PyImage::~PyImage() { py::gil_scoped_acquire acquire; sdk_py.dec_ref(); } void pycv::PyImage::GlobalInit(const std::string& model_dir, int gpu_id) { std::call_once(python_once, [] { python_interpreter_guard = std::unique_ptr( new py::scoped_interpreter()); { pybind11::gil_scoped_acquire acquire; } python_interpreter_gil_scoped_release = std::unique_ptr( new py::gil_scoped_release()); }); } void pycv::PyImage::GlobalRelease() {} void pycv::PyImage::LocalInit(const LocalInitRequest& req, LocalInitResponse& resp) { // acquiring GIL as toPyObject creates new py::object // without grabbing the GIL. py::gil_scoped_acquire acquire; // https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object.html#calling-python-methods // https://github.com/pybind/pybind11/issues/1201 auto py_cv = py::module::import("pycv"); if (py_cv.is_none()) { throw std::runtime_error("module pycv not found"); } if (!py::hasattr(py_cv, "CVSDK")) { throw std::runtime_error("python class pycv.CVSD not found"); } auto CVSDK = py_cv.attr("CVSDK"); sdk_py = CVSDK(); if (!py::hasattr(sdk_py, "init")) { throw std::runtime_error("python method py.CVSDK::init not found"); } if (!py::hasattr(sdk_py, "do")) { throw std::runtime_error("python method py.CVSDK::do not found"); } { // 模型初始化 py::dict dict("model_dir"_a = req.model_dir, "gpu_id"_a = req.gpu_id); dict["sdk_dir"] = req.sdk_dir; auto init_resp_py = sdk_py.attr("init")(**dict); auto init_resp = py::dict(init_resp_py); if (init_resp.contains("err")) { std::stringstream ss; ss << "py.CVSDK::init returns ("; ss << init_resp["err"].cast(); ss << ")"; throw std::runtime_error(ss.str()); } } } void pycv::PyImage::Do(const DoRequest& req, DoResponse& resp) { py::gil_scoped_acquire acquire; if (sdk_py.is_none()) { throw std::runtime_error( "method py.CVSDK not initialized, call init at first"); } if (!py::hasattr(sdk_py, "do")) { throw std::runtime_error("method py.do not found"); } { py::dict dict("arg1"_a = py::bytes(req.arg1)); dict["arg2"] = req.arg2; auto do_resp_py = sdk_py.attr("do")(**dict); auto do_resp = py::dict(do_resp_py); if (do_resp.contains("err")) { std::stringstream ss; ss << "py.CVSDK::do do_resp returns ("; ss << do_resp["err"].cast(); ss << ")"; throw std::runtime_error(ss.str()); } } } ================================================ FILE: pkg/gocv/cgo/swig/pycv/pycv_test.go ================================================ package pycv_test import ( "testing" "github.com/kaydxh/golang/pkg/gocv/cgo/swig/pycv" pycv_ "github.com/kaydxh/golang/pkg/gocv/cgo/swig/pycv" ) func TestDo(t *testing.T) { err := pycv_.GlobalInit("model_dir", -1) if err != nil { t.Error(err.Error()) return } defer pycv.GlobalRelease() sdk := pycv_.NewPyImage() initReq := pycv_.NewLocalInitRequest() _, err = sdk.LocalInit(initReq) if err != nil { t.Errorf("failed to local init, err: %v", err) } req := pycv_.NewDoRequest() req.SetArg1("arg1") req.SetArg2("arg2") _, err = sdk.Do(req) if err != nil { t.Error(err.Error()) return } } ================================================ FILE: pkg/gocv/cgo/swig/pycv/pycv_wrap.cxx ================================================ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (https://www.swig.org). * Version 4.1.1 * * Do not make changes to this file unless you know what you are doing - modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ // source: pycv.swigcxx extern #ifdef __cplusplus "C" #endif void cgo_panic__pycv_ffa8ea6aa3be9035(const char*); static void _swig_gopanic(const char *p) { cgo_panic__pycv_ffa8ea6aa3be9035(p); } #define SWIG_VERSION 0x040101 #define SWIGGO #define SWIGMODULE pycv #define SWIG_DIRECTORS /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if defined(__GNUC__) # if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif /* Deal with Apple's deprecated 'AssertMacros.h' from Carbon-framework */ #if defined(__APPLE__) && !defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES) # define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0 #endif /* Intel's compiler complains if a variable which was never initialised is * cast to void, which is a common idiom which we use to indicate that we * are aware a variable isn't used. So we just silence that warning. * See: https://github.com/swig/swig/issues/192 for more discussion. */ #ifdef __INTEL_COMPILER # pragma warning disable 592 #endif #include #include #include #include #include typedef long long intgo; typedef unsigned long long uintgo; # if !defined(__clang__) && (defined(__i386__) || defined(__x86_64__)) # define SWIGSTRUCTPACKED __attribute__((__packed__, __gcc_struct__)) # else # define SWIGSTRUCTPACKED __attribute__((__packed__)) # endif typedef struct { char *p; intgo n; } _gostring_; typedef struct { void* array; intgo len; intgo cap; } _goslice_; #define SWIG_exception(code, msg) _swig_gopanic(msg) static _gostring_ Swig_AllocateString(const char *p, size_t l) { _gostring_ ret; ret.p = (char*)malloc(l); memcpy(ret.p, p, l); ret.n = l; return ret; } /* ----------------------------------------------------------------------------- * director_common.swg * * This file contains support for director classes which is common between * languages. * ----------------------------------------------------------------------------- */ /* Use -DSWIG_DIRECTOR_STATIC if you prefer to avoid the use of the 'Swig' namespace. This could be useful for multi-modules projects. */ #ifdef SWIG_DIRECTOR_STATIC /* Force anonymous (static) namespace */ #define Swig #endif /* ----------------------------------------------------------------------------- * director.swg * * This file contains support for director classes so that Go proxy * methods can be called from C++. * ----------------------------------------------------------------------------- */ #include #include namespace Swig { class DirectorException : public std::exception { }; } /* Handle memory management for directors. */ namespace { struct GCItem { virtual ~GCItem() {} }; struct GCItem_var { GCItem_var(GCItem *item = 0) : _item(item) { } GCItem_var& operator=(GCItem *item) { GCItem *tmp = _item; _item = item; delete tmp; return *this; } ~GCItem_var() { delete _item; } GCItem* operator->() { return _item; } private: GCItem *_item; }; template struct GCItem_T : GCItem { GCItem_T(Type *ptr) : _ptr(ptr) { } virtual ~GCItem_T() { delete _ptr; } private: Type *_ptr; }; } class Swig_memory { public: template void swig_acquire_pointer(Type* vptr) { if (vptr) { swig_owner[vptr] = new GCItem_T(vptr); } } private: typedef std::map swig_ownership_map; swig_ownership_map swig_owner; }; template static void swig_acquire_pointer(Swig_memory** pmem, Type* ptr) { if (!pmem) { *pmem = new Swig_memory; } (*pmem)->swig_acquire_pointer(ptr); } #ifdef __cplusplus #include /* SwigValueWrapper is described in swig.swg */ template class SwigValueWrapper { struct SwigSmartPointer { T *ptr; SwigSmartPointer(T *p) : ptr(p) { } ~SwigSmartPointer() { delete ptr; } SwigSmartPointer& operator=(SwigSmartPointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } void reset(T *p) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = p; } } pointer; SwigValueWrapper& operator=(const SwigValueWrapper& rhs); SwigValueWrapper(const SwigValueWrapper& rhs); public: SwigValueWrapper() : pointer(0) { } SwigValueWrapper& operator=(const T& t) { SwigSmartPointer tmp(new T(t)); pointer = tmp; return *this; } #if __cplusplus >=201103L SwigValueWrapper& operator=(T&& t) { SwigSmartPointer tmp(new T(std::move(t))); pointer = tmp; return *this; } operator T&&() const { return std::move(*pointer.ptr); } #else operator T&() const { return *pointer.ptr; } #endif T *operator&() const { return pointer.ptr; } static void reset(SwigValueWrapper& t, T *p) { t.pointer.reset(p); } }; /* * SwigValueInit() is a generic initialisation solution as the following approach: * * T c_result = T(); * * doesn't compile for all types for example: * * unsigned int c_result = unsigned int(); */ template T SwigValueInit() { return T(); } #if __cplusplus >=201103L # define SWIG_STD_MOVE(OBJ) std::move(OBJ) #else # define SWIG_STD_MOVE(OBJ) OBJ #endif #endif static void Swig_free(void* p) { free(p); } static void* Swig_malloc(int c) { return malloc(c); } #include #include #include #include #include #include #include #include #include "pycv.h" // C++ director class methods. #include "pycv_wrap.h" #ifdef __cplusplus extern "C" { #endif void _wrap_Swig_free_pycv_ffa8ea6aa3be9035(void *_swig_go_0) { void *arg1 = (void *) 0 ; arg1 = *(void **)&_swig_go_0; Swig_free(arg1); } void *_wrap_Swig_malloc_pycv_ffa8ea6aa3be9035(intgo _swig_go_0) { int arg1 ; void *result = 0 ; void *_swig_go_result; arg1 = (int)_swig_go_0; result = (void *)Swig_malloc(arg1); *(void **)&_swig_go_result = (void *)result; return _swig_go_result; } void _wrap_LocalInitRequest_gpu_id_set_pycv_ffa8ea6aa3be9035(pycv::LocalInitRequest *_swig_go_0, intgo _swig_go_1) { pycv::LocalInitRequest *arg1 = (pycv::LocalInitRequest *) 0 ; int arg2 ; arg1 = *(pycv::LocalInitRequest **)&_swig_go_0; arg2 = (int)_swig_go_1; if (arg1) (arg1)->gpu_id = arg2; } intgo _wrap_LocalInitRequest_gpu_id_get_pycv_ffa8ea6aa3be9035(pycv::LocalInitRequest *_swig_go_0) { pycv::LocalInitRequest *arg1 = (pycv::LocalInitRequest *) 0 ; int result; intgo _swig_go_result; arg1 = *(pycv::LocalInitRequest **)&_swig_go_0; result = (int) ((arg1)->gpu_id); _swig_go_result = result; return _swig_go_result; } void _wrap_LocalInitRequest_sdk_dir_set_pycv_ffa8ea6aa3be9035(pycv::LocalInitRequest *_swig_go_0, _gostring_ _swig_go_1) { pycv::LocalInitRequest *arg1 = (pycv::LocalInitRequest *) 0 ; std::string *arg2 = 0 ; arg1 = *(pycv::LocalInitRequest **)&_swig_go_0; std::string arg2_str(_swig_go_1.p, _swig_go_1.n); arg2 = &arg2_str; if (arg1) (arg1)->sdk_dir = *arg2; } _gostring_ _wrap_LocalInitRequest_sdk_dir_get_pycv_ffa8ea6aa3be9035(pycv::LocalInitRequest *_swig_go_0) { pycv::LocalInitRequest *arg1 = (pycv::LocalInitRequest *) 0 ; std::string *result = 0 ; _gostring_ _swig_go_result; arg1 = *(pycv::LocalInitRequest **)&_swig_go_0; result = (std::string *) & ((arg1)->sdk_dir); _swig_go_result = Swig_AllocateString((*result).data(), (*result).length()); return _swig_go_result; } void _wrap_LocalInitRequest_model_dir_set_pycv_ffa8ea6aa3be9035(pycv::LocalInitRequest *_swig_go_0, _gostring_ _swig_go_1) { pycv::LocalInitRequest *arg1 = (pycv::LocalInitRequest *) 0 ; std::string *arg2 = 0 ; arg1 = *(pycv::LocalInitRequest **)&_swig_go_0; std::string arg2_str(_swig_go_1.p, _swig_go_1.n); arg2 = &arg2_str; if (arg1) (arg1)->model_dir = *arg2; } _gostring_ _wrap_LocalInitRequest_model_dir_get_pycv_ffa8ea6aa3be9035(pycv::LocalInitRequest *_swig_go_0) { pycv::LocalInitRequest *arg1 = (pycv::LocalInitRequest *) 0 ; std::string *result = 0 ; _gostring_ _swig_go_result; arg1 = *(pycv::LocalInitRequest **)&_swig_go_0; result = (std::string *) & ((arg1)->model_dir); _swig_go_result = Swig_AllocateString((*result).data(), (*result).length()); return _swig_go_result; } pycv::LocalInitRequest *_wrap_new_LocalInitRequest_pycv_ffa8ea6aa3be9035() { pycv::LocalInitRequest *result = 0 ; pycv::LocalInitRequest *_swig_go_result; { try { result = (pycv::LocalInitRequest *)new pycv::LocalInitRequest();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(pycv::LocalInitRequest **)&_swig_go_result = (pycv::LocalInitRequest *)result; return _swig_go_result; } void _wrap_delete_LocalInitRequest_pycv_ffa8ea6aa3be9035(pycv::LocalInitRequest *_swig_go_0) { pycv::LocalInitRequest *arg1 = (pycv::LocalInitRequest *) 0 ; arg1 = *(pycv::LocalInitRequest **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } pycv::LocalInitResponse *_wrap_new_LocalInitResponse_pycv_ffa8ea6aa3be9035() { pycv::LocalInitResponse *result = 0 ; pycv::LocalInitResponse *_swig_go_result; { try { result = (pycv::LocalInitResponse *)new pycv::LocalInitResponse();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(pycv::LocalInitResponse **)&_swig_go_result = (pycv::LocalInitResponse *)result; return _swig_go_result; } void _wrap_delete_LocalInitResponse_pycv_ffa8ea6aa3be9035(pycv::LocalInitResponse *_swig_go_0) { pycv::LocalInitResponse *arg1 = (pycv::LocalInitResponse *) 0 ; arg1 = *(pycv::LocalInitResponse **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } void _wrap_DoRequest_arg1_set_pycv_ffa8ea6aa3be9035(pycv::DoRequest *_swig_go_0, _gostring_ _swig_go_1) { pycv::DoRequest *arg1 = (pycv::DoRequest *) 0 ; std::string *arg2 = 0 ; arg1 = *(pycv::DoRequest **)&_swig_go_0; std::string arg2_str(_swig_go_1.p, _swig_go_1.n); arg2 = &arg2_str; if (arg1) (arg1)->arg1 = *arg2; } _gostring_ _wrap_DoRequest_arg1_get_pycv_ffa8ea6aa3be9035(pycv::DoRequest *_swig_go_0) { pycv::DoRequest *arg1 = (pycv::DoRequest *) 0 ; std::string *result = 0 ; _gostring_ _swig_go_result; arg1 = *(pycv::DoRequest **)&_swig_go_0; result = (std::string *) & ((arg1)->arg1); _swig_go_result = Swig_AllocateString((*result).data(), (*result).length()); return _swig_go_result; } void _wrap_DoRequest_arg2_set_pycv_ffa8ea6aa3be9035(pycv::DoRequest *_swig_go_0, _gostring_ _swig_go_1) { pycv::DoRequest *arg1 = (pycv::DoRequest *) 0 ; std::string *arg2 = 0 ; arg1 = *(pycv::DoRequest **)&_swig_go_0; std::string arg2_str(_swig_go_1.p, _swig_go_1.n); arg2 = &arg2_str; if (arg1) (arg1)->arg2 = *arg2; } _gostring_ _wrap_DoRequest_arg2_get_pycv_ffa8ea6aa3be9035(pycv::DoRequest *_swig_go_0) { pycv::DoRequest *arg1 = (pycv::DoRequest *) 0 ; std::string *result = 0 ; _gostring_ _swig_go_result; arg1 = *(pycv::DoRequest **)&_swig_go_0; result = (std::string *) & ((arg1)->arg2); _swig_go_result = Swig_AllocateString((*result).data(), (*result).length()); return _swig_go_result; } pycv::DoRequest *_wrap_new_DoRequest_pycv_ffa8ea6aa3be9035() { pycv::DoRequest *result = 0 ; pycv::DoRequest *_swig_go_result; { try { result = (pycv::DoRequest *)new pycv::DoRequest();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(pycv::DoRequest **)&_swig_go_result = (pycv::DoRequest *)result; return _swig_go_result; } void _wrap_delete_DoRequest_pycv_ffa8ea6aa3be9035(pycv::DoRequest *_swig_go_0) { pycv::DoRequest *arg1 = (pycv::DoRequest *) 0 ; arg1 = *(pycv::DoRequest **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } pycv::DoResponse *_wrap_new_DoResponse_pycv_ffa8ea6aa3be9035() { pycv::DoResponse *result = 0 ; pycv::DoResponse *_swig_go_result; { try { result = (pycv::DoResponse *)new pycv::DoResponse();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(pycv::DoResponse **)&_swig_go_result = (pycv::DoResponse *)result; return _swig_go_result; } void _wrap_delete_DoResponse_pycv_ffa8ea6aa3be9035(pycv::DoResponse *_swig_go_0) { pycv::DoResponse *arg1 = (pycv::DoResponse *) 0 ; arg1 = *(pycv::DoResponse **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } pycv::PyImage *_wrap_new_Wrapped_PyImage_pycv_ffa8ea6aa3be9035() { pycv::PyImage *result = 0 ; pycv::PyImage *_swig_go_result; { try { result = (pycv::PyImage *)new pycv::PyImage();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } *(pycv::PyImage **)&_swig_go_result = (pycv::PyImage *)result; return _swig_go_result; } void _wrap_delete_Wrapped_PyImage_pycv_ffa8ea6aa3be9035(pycv::PyImage *_swig_go_0) { pycv::PyImage *arg1 = (pycv::PyImage *) 0 ; arg1 = *(pycv::PyImage **)&_swig_go_0; { try { delete arg1;; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } void _wrap_Wrapped_PyImage_GlobalInit_pycv_ffa8ea6aa3be9035(_gostring_ _swig_go_0, intgo _swig_go_1) { std::string *arg1 = 0 ; int arg2 ; std::string arg1_str(_swig_go_0.p, _swig_go_0.n); arg1 = &arg1_str; arg2 = (int)_swig_go_1; { try { pycv::PyImage::GlobalInit((std::string const &)*arg1,arg2);; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } void _wrap_Wrapped_PyImage_GlobalRelease_pycv_ffa8ea6aa3be9035() { { try { pycv::PyImage::GlobalRelease();; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } void _wrap_Wrapped_PyImage_Wrapped_PyImage_LocalInit_pycv_ffa8ea6aa3be9035(pycv::PyImage *_swig_go_0, pycv::LocalInitRequest *_swig_go_1, pycv::LocalInitResponse *_swig_go_2) { pycv::PyImage *arg1 = (pycv::PyImage *) 0 ; pycv::LocalInitRequest *arg2 = 0 ; pycv::LocalInitResponse *arg3 = 0 ; arg1 = *(pycv::PyImage **)&_swig_go_0; arg2 = *(pycv::LocalInitRequest **)&_swig_go_1; arg3 = *(pycv::LocalInitResponse **)&_swig_go_2; { try { (arg1)->LocalInit((pycv::LocalInitRequest const &)*arg2,*arg3);; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } void _wrap_Wrapped_PyImage_Wrapped_PyImage_Do_pycv_ffa8ea6aa3be9035(pycv::PyImage *_swig_go_0, pycv::DoRequest *_swig_go_1, pycv::DoResponse *_swig_go_2) { pycv::PyImage *arg1 = (pycv::PyImage *) 0 ; pycv::DoRequest *arg2 = 0 ; pycv::DoResponse *arg3 = 0 ; arg1 = *(pycv::PyImage **)&_swig_go_0; arg2 = *(pycv::DoRequest **)&_swig_go_1; arg3 = *(pycv::DoResponse **)&_swig_go_2; { try { (arg1)->Do((pycv::DoRequest const &)*arg2,*arg3);; } catch (const std::exception& e) { _swig_gopanic(e.what()); } } } #ifdef __cplusplus } #endif ================================================ FILE: pkg/gocv/cgo/swig/pycv/pycv_wrap.h ================================================ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (https://www.swig.org). * Version 4.1.1 * * Do not make changes to this file unless you know what you are doing - modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ // source: pycv.swigcxx #ifndef SWIG_pycv_WRAP_H_ #define SWIG_pycv_WRAP_H_ class Swig_memory; #endif ================================================ FILE: pkg/gocv/cgo/swig/types/pybind11/pybind11.swigcxx ================================================ //go:build ignore %header %{ #ifndef __SDK_CGO_UNKNOWN_PLATFORM__ #include #endif %} namespace pybind11 { class object {}; } // namespace pybind11 ================================================ FILE: pkg/gocv/cgo/swig/types/pybind11/pybind11_mock.h ================================================ #ifndef SDK_GO_PYBIND11_MOCK_H #define SDK_GO_PYBIND11_MOCK_H #include namespace pybind11 { class object {}; } // namespace pybind11 #endif // YT_SDK_GO_PYBIND11_MOCK_H ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/bin/GraphicsMagick++-config ================================================ #!/bin/sh # # Configure options script for re-calling compilation # options required to use the Magick++ library. # # Concept derived from gtk-config in the Gtk package except that Autoconf-style # configuration information is presented instead so that it may be used more # effictively in configure scripts. # usage='Usage: GraphicsMagick++-config [--cppflags] [--cxxflags] [--exec-prefix] [--ldflags] [--libs] [--prefix] [--version] For example, "example.cpp" may be compiled to produce "example" as follows: "c++ -o example example.cpp `GraphicsMagick++-config --cppflags --cxxflags --ldflags --libs`"' if test $# -eq 0; then echo "${usage}" 1>&2 exit 1 fi while test $# -gt 0; do case $1 in --prefix) echo /root/pinwoodxu/GraphicsMagick-source/release ;; --exec-prefix) echo /root/pinwoodxu/GraphicsMagick-source/release ;; --version) echo 1.3.35 ;; --cppflags) echo '-I/root/pinwoodxu/GraphicsMagick-source/release/include/GraphicsMagick' ;; --cxxflags) echo '-pthread' ;; --ldflags) echo '-L/root/pinwoodxu/GraphicsMagick-source/release/lib ' ;; --libs) echo '-lGraphicsMagick++ -lGraphicsMagick -lwebp -lwebpmux -ltiff -ljpeg -lpng15 -lbz2 -lz -lm -lpthread -lgomp' ;; *) echo "${usage}" 1>&2 exit 1 ;; esac shift done ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/bin/GraphicsMagick-config ================================================ #!/bin/sh # # Configure options script for re-calling GraphicsMagick compilation # options required to use the GraphicsMagick library. # # Concept derived from gtk-config in the Gtk package except that Autoconf-style # configuration information is presented instead so that it may be used more # effectively in configure scripts. # usage='Usage: GraphicsMagick-config [--cflags] [--cppflags] [--exec-prefix] [--ldflags] [--libs] [--prefix] [--version] For example, "example.c" may be compiled to produce "example" as follows: "gcc -o example example.c `GraphicsMagick-config --cppflags --cflags --ldflags --libs`"' if test $# -eq 0; then echo "${usage}" 1>&2 exit 1 fi while test $# -gt 0; do case $1 in --prefix) echo /root/pinwoodxu/GraphicsMagick-source/release ;; --exec-prefix) echo /root/pinwoodxu/GraphicsMagick-source/release ;; --version) echo 1.3.35 ;; --cflags) echo '-fopenmp -g -O2 -Wall -pthread' ;; --cppflags) echo '-I/root/pinwoodxu/GraphicsMagick-source/release/include/GraphicsMagick' ;; --ldflags) echo '-L/root/pinwoodxu/GraphicsMagick-source/release/lib ' ;; --libs) echo '-lGraphicsMagick -lwebp -lwebpmux -ltiff -ljpeg -lpng15 -lbz2 -lz -lm -lpthread -lgomp' ;; *) echo "${usage}" 1>&2 exit 1 ;; esac shift done ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/bin/GraphicsMagickWand-config ================================================ #!/bin/sh # # Configure options script for re-calling GraphicsMagick compilation # options required to use the GraphicsMagick Wand library. # # Concept derived from gtk-config in the Gtk package except that Autoconf-style # configuration information is presented instead so that it may be used more # effectively in configure scripts. # usage='Usage: GraphicsMagickWand-config [--cflags] [--cppflags] [--exec-prefix] [--ldflags] [--libs] [--prefix] [--version] For example, "example.c" may be compiled to produce "example" as follows: "gcc -o example example.c `GraphicsMagickWand-config --cppflags --cflags --ldflags --libs`"' if test $# -eq 0; then echo "${usage}" 1>&2 exit 1 fi while test $# -gt 0; do case $1 in --prefix) echo /root/pinwoodxu/GraphicsMagick-source/release ;; --exec-prefix) echo /root/pinwoodxu/GraphicsMagick-source/release ;; --version) echo 1.3.35 ;; --cflags) echo "`GraphicsMagick-config --cflags`" ;; --cppflags) echo "`GraphicsMagick-config --cppflags`" ;; --ldflags) echo "`GraphicsMagick-config --ldflags`" ;; --libs) echo "-lGraphicsMagickWand `GraphicsMagick-config --libs`" ;; *) echo "${usage}" 1>&2 exit 1 ;; esac shift done ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Blob.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002 // // Reference counted container class for Binary Large Objects (BLOBs) // #if !defined(Magick_BlobRef_header) #define Magick_BlobRef_header #include "Magick++/Include.h" #include namespace Magick { // Forward decl class BlobRef; class MagickDLLDecl Blob { public: enum Allocator { MallocAllocator, NewAllocator }; // Default constructor Blob ( void ); // Construct object with data, making a copy of the supplied data. Blob ( const void* data_, size_t length_ ); // Copy constructor (reference counted) Blob ( const Blob& blob_ ); // Destructor (reference counted) virtual ~Blob (); // Assignment operator (reference counted) Blob& operator= ( const Blob& blob_ ); // Update object contents from Base64-encoded string representation. void base64 ( const std::string base64_ ); // Return Base64-encoded string representation. std::string base64 ( void ); // Update object contents, making a copy of the supplied data. // Any existing data in the object is deallocated. void update ( const void* data_, size_t length_ ); // Update object contents, using supplied pointer directly (no // copy). Any existing data in the object is deallocated. The user // must ensure that the pointer supplied is not deleted or // otherwise modified after it has been supplied to this method. // Specify allocator_ as "MallocAllocator" if memory is allocated // via the C language malloc() function, or "NewAllocator" if // memory is allocated via C++ 'new'. void updateNoCopy ( void* data_, size_t length_, Allocator allocator_ = NewAllocator ); // Obtain pointer to data. The user should never try to modify or // free this data since the Blob class manages its own data. The // user must be finished with the data before allowing the Blob to // be destroyed since the pointer is invalid once the Blob is // destroyed. const void* data ( void ) const; // Obtain data length size_t length ( void ) const; protected: private: BlobRef * _blobRef; }; } // namespace Magick #endif // Magick_BlobRef_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/CoderInfo.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 2001-2010 // // CoderInfo Definition // // Container for image format support information. // #if !defined (Magick_CoderInfo_header) #define Magick_CoderInfo_header #include "Magick++/Include.h" #include namespace Magick { class MagickDLLDecl CoderInfo { public: enum MatchType { AnyMatch, // match any coder TrueMatch, // match coder if true FalseMatch // match coder if false }; // Default constructor CoderInfo ( void ); // Copy constructor CoderInfo ( const CoderInfo &coder_ ); // Construct with coder name CoderInfo ( const std::string &name_ ); // Destructor ~CoderInfo ( void ); // Format name std::string name( void ) const; // Format description std::string description( void ) const; // Format is readable bool isReadable( void ) const; // Format is writeable bool isWritable( void ) const; // Format supports multiple frames bool isMultiFrame( void ) const; // Assignment operator CoderInfo& operator= (const CoderInfo &coder_ ); // // Implemementation methods // CoderInfo ( const MagickLib::MagickInfo *magickInfo_ ); private: std::string _name; std::string _description; bool _isReadable; bool _isWritable; bool _isMultiFrame; }; } // namespace Magick // // Inlines // #endif // Magick_CoderInfo_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Color.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003, 2008 // // Color Implementation // #if !defined (Magick_Color_header) #define Magick_Color_header #include "Magick++/Include.h" #include namespace Magick { class MagickDLLDecl Color; // Compare two Color objects regardless of LHS/RHS int MagickDLLDecl operator == ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator != ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator > ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator < ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator >= ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator <= ( const Magick::Color& left_, const Magick::Color& right_ ); // Base color class stores RGB components scaled to fit Quantum class MagickDLLDecl Color { public: Color ( Quantum red_, Quantum green_, Quantum blue_ ); Color ( Quantum red_, Quantum green_, Quantum blue_, Quantum alpha_ ); Color ( const std::string &x11color_ ); Color ( const char * x11color_ ); Color ( void ); virtual ~Color ( void ); Color ( const Color & color_ ); // Red color (range 0 to MaxRGB) void redQuantum ( Quantum red_ ); Quantum redQuantum ( void ) const; // Green color (range 0 to MaxRGB) void greenQuantum ( Quantum green_ ); Quantum greenQuantum ( void ) const; // Blue color (range 0 to MaxRGB) void blueQuantum ( Quantum blue_ ); Quantum blueQuantum ( void ) const; // Alpha level (range OpaqueOpacity=0 to TransparentOpacity=MaxRGB) void alphaQuantum ( Quantum alpha_ ); Quantum alphaQuantum ( void ) const; // Scaled (to 1.0) version of alpha for use in sub-classes // (range opaque=0 to transparent=1.0) void alpha ( double alpha_ ); double alpha ( void ) const; // Does object contain valid color? void isValid ( bool valid_ ); bool isValid ( void ) const; // Set color via X11 color specification string const Color& operator= ( const std::string &x11color_ ); const Color& operator= ( const char * x11color_ ); // Assignment operator Color& operator= ( const Color& color_ ); // Return X11 color specification string /* virtual */ operator std::string() const; // Return ImageMagick PixelPacket operator PixelPacket() const; // Construct color via ImageMagick PixelPacket Color ( const PixelPacket &color_ ); // Set color via ImageMagick PixelPacket const Color& operator= ( const PixelPacket &color_ ); // // Public methods beyond this point are for Magick++ use only. // // Obtain pixel intensity as a double double intensity ( void ) const { return (0.299*(_pixel->red)+0.587*(_pixel->green)+0.114*(_pixel->blue)); } // Scale a value expressed as a double (0-1) to Quantum range (0-MaxRGB) static Quantum scaleDoubleToQuantum( const double double_ ) { return (static_cast(double_*MaxRGB)); } // Scale a value expressed as a Quantum (0-MaxRGB) to double range (0-1) static double scaleQuantumToDouble( const Quantum quantum_ ) { return (static_cast(quantum_)/MaxRGB); } static double scaleQuantumToDouble( const double quantum_ ) { return (quantum_/MaxRGB); } protected: // PixelType specifies the interpretation of PixelPacket members // RGBPixel: // Red = red; // Green = green; // Blue = blue; // RGBAPixel: // Red = red; // Green = green; // Blue = blue; // Alpha = opacity; // CYMKPixel: // Cyan = red // Yellow = green // Magenta = blue // Black(K) = opacity enum PixelType { RGBPixel, RGBAPixel, CYMKPixel }; // Constructor to construct with PixelPacket* // Used to point Color at a pixel in an image Color ( PixelPacket* rep_, PixelType pixelType_ ); // Set pixel // Used to point Color at a pixel in an image void pixel ( PixelPacket* rep_, PixelType pixelType_ ); // PixelPacket represents a color pixel: // red = red (range 0 to MaxRGB) // green = green (range 0 to MaxRGB) // blue = blue (range 0 to MaxRGB) // opacity = alpha (range OpaqueOpacity=0 to TransparentOpacity=MaxRGB) // index = PseudoColor colormap index PixelPacket* _pixel; private: // Common initializer for PixelPacket representation void initPixel(); // Set true if we allocated pixel bool _pixelOwn; // Set true if pixel is "valid" bool _isValid; // Color type supported by _pixel PixelType _pixelType; }; // // HSL Colorspace colors // class MagickDLLDecl ColorHSL : public Color { public: ColorHSL ( double hue_, double saturation_, double luminosity_ ); ColorHSL ( void ); ColorHSL ( const Color & color_ ); /* virtual */ ~ColorHSL ( ); void hue ( double hue_ ); double hue ( void ) const; void saturation ( double saturation_ ); double saturation ( void ) const; void luminosity ( double luminosity_ ); double luminosity ( void ) const; // Assignment operator from base class ColorHSL& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorHSL ( PixelPacket* rep_, PixelType pixelType_ ); }; // // Grayscale RGB color // // Grayscale is simply RGB with equal parts of red, green, and blue // All double arguments have a valid range of 0.0 - 1.0. class MagickDLLDecl ColorGray : public Color { public: ColorGray ( double shade_ ); ColorGray ( void ); ColorGray ( const Color & color_ ); /* virtual */ ~ColorGray (); void shade ( double shade_ ); double shade ( void ) const; // Assignment operator from base class ColorGray& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorGray ( PixelPacket* rep_, PixelType pixelType_ ); }; // // Monochrome color // // Color arguments are constrained to 'false' (black pixel) and 'true' // (white pixel) class MagickDLLDecl ColorMono : public Color { public: ColorMono ( bool mono_ ); ColorMono ( void ); ColorMono ( const Color & color_ ); /* virtual */ ~ColorMono (); void mono ( bool mono_ ); bool mono ( void ) const; // Assignment operator from base class ColorMono& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorMono ( PixelPacket* rep_, PixelType pixelType_ ); }; // // RGB color // // All color arguments have a valid range of 0.0 - 1.0. class MagickDLLDecl ColorRGB : public Color { public: ColorRGB ( double red_, double green_, double blue_ ); ColorRGB ( void ); ColorRGB ( const Color & color_ ); /* virtual */ ~ColorRGB ( void ); void red ( double red_ ); double red ( void ) const; void green ( double green_ ); double green ( void ) const; void blue ( double blue_ ); double blue ( void ) const; // Assignment operator from base class ColorRGB& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorRGB ( PixelPacket* rep_, PixelType pixelType_ ); }; // // YUV Colorspace color // // Argument ranges: // Y: 0.0 through 1.0 // U: -0.5 through 0.5 // V: -0.5 through 0.5 class MagickDLLDecl ColorYUV : public Color { public: ColorYUV ( double y_, double u_, double v_ ); ColorYUV ( void ); ColorYUV ( const Color & color_ ); /* virtual */ ~ColorYUV ( void ); void u ( double u_ ); double u ( void ) const; void v ( double v_ ); double v ( void ) const; void y ( double y_ ); double y ( void ) const; // Assignment operator from base class ColorYUV& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorYUV ( PixelPacket* rep_, PixelType pixelType_ ); }; } // namespace Magick // // Inlines // // // Color // // Common initializer for PixelPacket representation // Initialized transparent black inline void Magick::Color::initPixel() { _pixel->red = 0; _pixel->green = 0; _pixel->blue = 0; _pixel->opacity = TransparentOpacity; } inline void Magick::Color::redQuantum ( Magick::Quantum red_ ) { _pixel->red = red_; _isValid = true; } inline Magick::Quantum Magick::Color::redQuantum ( void ) const { return _pixel->red; } inline void Magick::Color::greenQuantum ( Magick::Quantum green_ ) { _pixel->green = green_; _isValid = true; } inline Magick::Quantum Magick::Color::greenQuantum ( void ) const { return _pixel->green; } inline void Magick::Color::blueQuantum ( Magick::Quantum blue_ ) { _pixel->blue = blue_; _isValid = true; } inline Magick::Quantum Magick::Color::blueQuantum ( void ) const { return _pixel->blue; } inline void Magick::Color::alphaQuantum ( Magick::Quantum alpha_ ) { _pixel->opacity = alpha_; _isValid = true ; } inline Magick::Quantum Magick::Color::alphaQuantum ( void ) const { return _pixel->opacity; } // Return ImageMagick PixelPacket struct based on color. inline Magick::Color::operator MagickLib::PixelPacket () const { return *_pixel; } // Scaled version of alpha for use in sub-classes inline void Magick::Color::alpha ( double alpha_ ) { alphaQuantum( scaleDoubleToQuantum(alpha_) ); } inline double Magick::Color::alpha ( void ) const { return scaleQuantumToDouble( alphaQuantum() ); } // // ColorHSL // inline Magick::ColorHSL::ColorHSL ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } // // ColorGray // inline Magick::ColorGray::ColorGray ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } // // ColorMono // inline Magick::ColorMono::ColorMono ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } // // ColorRGB // inline Magick::ColorRGB::ColorRGB ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } inline void Magick::ColorRGB::red ( double red_ ) { redQuantum( scaleDoubleToQuantum(red_) ); } inline double Magick::ColorRGB::red ( void ) const { return scaleQuantumToDouble( redQuantum() ); } inline void Magick::ColorRGB::green ( double green_ ) { greenQuantum( scaleDoubleToQuantum(green_) ); } inline double Magick::ColorRGB::green ( void ) const { return scaleQuantumToDouble( greenQuantum() ); } inline void Magick::ColorRGB::blue ( double blue_ ) { blueQuantum( scaleDoubleToQuantum(blue_) ); } inline double Magick::ColorRGB::blue ( void ) const { return scaleQuantumToDouble( blueQuantum() ); } // // ColorYUV // inline Magick::ColorYUV::ColorYUV ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } #endif // Magick_Color_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Drawable.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2018 // // Definition of Drawable (Graphic objects) // // The technique used for instantiating classes which derive from STL // templates is described in Microsoft MSDN Article ID: Q168958 // "HOWTO: Exporting STL Components Inside & Outside of a Class". // "http://support.microsoft.com/kb/168958" // // Note that version 3.0 of this article says that that only STL // container template which supports DLL export is and we are // not using as part of the Drawable implementation. // #if !defined(Magick_Drawable_header) #define Magick_Drawable_header #include "Magick++/Include.h" #include #include #include #include #include "Magick++/Color.h" #include "Magick++/Geometry.h" #if defined(MagickDLLExplicitTemplate) # if defined(MAGICK_PLUSPLUS_IMPLEMENTATION) # define MagickDrawableExtern # else # pragma warning( disable: 4231 ) // Disable warning regarding using extern # define MagickDrawableExtern extern # endif // MAGICK_PLUSPLUS_IMPLEMENTATION #else # define MagickDrawableExtern #endif // MagickDLLExplicitTemplate namespace Magick { #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-warning-option" #pragma clang diagnostic ignored "-Wunused-private-field" #endif /* if defined(__clang__) */ // // Representation of an x,y coordinate // class MagickDLLDecl Coordinate { public: // Default Constructor Coordinate ( void ) : _x(0), _y(0) { } // Constructor, setting first & second Coordinate ( double x_, double y_ ) : _x(x_), _y(y_) { } // Destructor virtual ~Coordinate () { } // x coordinate member void x ( double x_ ) { _x = x_; } double x ( void ) const { return _x; } // y coordinate member void y ( double y_ ) { _y = y_; } double y ( void ) const { return _y; } private: double _x; double _y; }; typedef std::list CoordinateList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate // Compare two Coordinate objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator != ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator > ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator < ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator >= ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator <= ( const Coordinate& left_, const Coordinate& right_ ); // // Base class for all drawable objects // //struct MagickDLLDecl std::unary_function; class MagickDLLDecl DrawableBase: public std::unary_function { public: // Constructor DrawableBase ( void ) { } // Destructor virtual ~DrawableBase ( void ); // Operator to invoke equivalent draw API call virtual void operator()( MagickLib::DrawContext ) const = 0; // Return polymorphic copy of object virtual DrawableBase* copy() const = 0; private: }; // // Representation of a drawable surrogate object to manage drawable objects // #undef Drawable // Conflict with class MagickDLLDecl Drawable { public: // Constructor Drawable ( void ); // Construct from DrawableBase Drawable ( const DrawableBase& original_ ); // Destructor ~Drawable ( void ); // Copy constructor Drawable ( const Drawable& original_ ); // Assignment operator Drawable& operator= (const Drawable& original_ ); // Operator to invoke contained object void operator()( MagickLib::DrawContext context_ ) const; private: DrawableBase* dp; }; // Compare two Drawable objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator != ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator > ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator < ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator >= ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator <= ( const Drawable& left_, const Drawable& right_ ); typedef std::list DrawableList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate // // Base class for all drawable path elements for use with // DrawablePath // class MagickDLLDecl VPathBase { public: // Constructor VPathBase ( void ) { } // Destructor virtual ~VPathBase ( void ); // Assignment operator // const VPathBase& operator= (const VPathBase& original_ ); // Operator to invoke equivalent draw API call virtual void operator()( MagickLib::DrawContext context_ ) const = 0; // Return polymorphic copy of object virtual VPathBase* copy() const = 0; }; // // Representation of a drawable path element surrogate object to // manage drawable path elements so they may be passed as a list to // DrawablePath. // class MagickDLLDecl VPath { public: // Constructor VPath ( void ); // Construct from VPathBase VPath ( const VPathBase& original_ ); // Destructor virtual ~VPath ( void ); // Copy constructor VPath ( const VPath& original_ ); // Assignment operator VPath& operator= (const VPath& original_ ); // Operator to invoke contained object void operator()( MagickLib::DrawContext context_ ) const; private: VPathBase* dp; }; // Compare two VPath objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator != ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator > ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator < ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator >= ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator <= ( const VPath& left_, const VPath& right_ ); typedef std::list VPathList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate // // Drawable Objects // // Affine (scaling, rotation, and translation) class MagickDLLDecl DrawableAffine : public DrawableBase { public: DrawableAffine ( double sx_, double sy_, double rx_, double ry_, double tx_, double ty_ ); DrawableAffine ( void ); /*virtual*/ ~DrawableAffine( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void sx( const double sx_ ) { _affine.sx = sx_; } double sx( void ) const { return _affine.sx; } void sy( const double sy_ ) { _affine.sy = sy_; } double sy( void ) const { return _affine.sy; } void rx( const double rx_ ) { _affine.rx = rx_; } double rx( void ) const { return _affine.rx; } void ry( const double ry_ ) { _affine.ry = ry_; } double ry( void ) const { return _affine.ry; } void tx( const double tx_ ) { _affine.tx = tx_; } double tx( void ) const { return _affine.tx; } void ty( const double ty_ ) { _affine.ty = ty_; } double ty( void ) const { return _affine.ty; } private: MagickLib::AffineMatrix _affine; }; // Arc class MagickDLLDecl DrawableArc : public DrawableBase { public: DrawableArc ( double startX_, double startY_, double endX_, double endY_, double startDegrees_, double endDegrees_ ) : _startX(startX_), _startY(startY_), _endX(endX_), _endY(endY_), _startDegrees(startDegrees_), _endDegrees(endDegrees_) { } /*virtual*/ ~DrawableArc( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void startX( double startX_ ) { _startX = startX_; } double startX( void ) const { return _startX; } void startY( double startY_ ) { _startY = startY_; } double startY( void ) const { return _startY; } void endX( double endX_ ) { _endX = endX_; } double endX( void ) const { return _endX; } void endY( double endY_ ) { _endY = endY_; } double endY( void ) const { return _endY; } void startDegrees( double startDegrees_ ) { _startDegrees = startDegrees_; } double startDegrees( void ) const { return _startDegrees; } void endDegrees( double endDegrees_ ) { _endDegrees = endDegrees_; } double endDegrees( void ) const { return _endDegrees; } private: double _startX; double _startY; double _endX; double _endY; double _startDegrees; double _endDegrees; }; // Bezier curve (Coordinate list must contain at least three members) class MagickDLLDecl DrawableBezier : public DrawableBase { public: // Construct from coordinates DrawableBezier ( const CoordinateList &coordinates_ ); // Copy constructor DrawableBezier ( const DrawableBezier& original_ ); // Destructor /*virtual*/ ~DrawableBezier ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: CoordinateList _coordinates; }; // Pop (terminate) clip path definition class MagickDLLDecl DrawablePopClipPath : public DrawableBase { public: DrawablePopClipPath ( void ) : _dummy(0) { } /*virtual*/ ~DrawablePopClipPath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: int _dummy; }; // Push (create) Clip path definition class MagickDLLDecl DrawablePushClipPath : public DrawableBase { public: DrawablePushClipPath ( const std::string &id_); DrawablePushClipPath ( const DrawablePushClipPath& original_ ); /*virtual*/ ~DrawablePushClipPath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: std::string _id; }; // Named Clip Path class MagickDLLDecl DrawableClipPath : public DrawableBase { public: DrawableClipPath ( const std::string &id_ ); DrawableClipPath ( const DrawableClipPath& original_ ); /*virtual*/ ~DrawableClipPath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void clip_path( const std::string &id_ ) { _id = id_.c_str(); //multithread safe } std::string clip_path( void ) const { return _id; } private: std::string _id; }; // Circle class MagickDLLDecl DrawableCircle : public DrawableBase { public: DrawableCircle ( double originX_, double originY_, double perimX_, double perimY_ ) : _originX(originX_), _originY(originY_), _perimX(perimX_), _perimY(perimY_) { } /*virtual*/ ~DrawableCircle ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void originX( double originX_ ) { _originX = originX_; } double originX( void ) const { return _originX; } void originY( double originY_ ) { _originY = originY_; } double originY( void ) const { return _originY; } void perimX( double perimX_ ) { _perimX = perimX_; } double perimX( void ) const { return _perimX; } void perimY( double perimY_ ) { _perimY = perimY_; } double perimY( void ) const { return _perimY; } private: double _originX; double _originY; double _perimX; double _perimY; }; // Colorize at point using PaintMethod class MagickDLLDecl DrawableColor : public DrawableBase { public: DrawableColor ( double x_, double y_, PaintMethod paintMethod_ ) : _x(x_), _y(y_), _paintMethod(paintMethod_) { } /*virtual*/ ~DrawableColor ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } void paintMethod( PaintMethod paintMethod_ ) { _paintMethod = paintMethod_; } PaintMethod paintMethod( void ) const { return _paintMethod; } private: double _x; double _y; PaintMethod _paintMethod; }; // Draw image at point, scaled to size specified by width and height class MagickDLLDecl Image; class MagickDLLDecl DrawableCompositeImage : public DrawableBase { public: DrawableCompositeImage ( double x_, double y_, const std::string &filename_ ); DrawableCompositeImage ( double x_, double y_, const Image &image_ ); DrawableCompositeImage ( double x_, double y_, double width_, double height_, const std::string &filename_ ); DrawableCompositeImage ( double x_, double y_, double width_, double height_, const Image &image_ ); DrawableCompositeImage ( double x_, double y_, double width_, double height_, const std::string &filename_, CompositeOperator composition_ ); DrawableCompositeImage ( double x_, double y_, double width_, double height_, const Image &image_, CompositeOperator composition_ ); // Copy constructor DrawableCompositeImage ( const DrawableCompositeImage& original_ ); // Destructor /*virtual*/ ~DrawableCompositeImage( void ); // Assignment operator DrawableCompositeImage& operator= (const DrawableCompositeImage& original_ ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void composition( CompositeOperator composition_ ) { _composition = composition_; } CompositeOperator composition( void ) const { return _composition; } void filename( const std::string &image_ ); std::string filename( void ) const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } void width( double width_ ) { _width = width_; } double width( void ) const { return _width; } void height( double height_ ) { _height = height_; } double height( void ) const { return _height; } void image( const Image &image_ ); Magick::Image image( void ) const; // Specify image format used to output Base64 inlined image data. void magick( std::string magick_ ); std::string magick( void ); private: CompositeOperator _composition; double _x; double _y; double _width; double _height; Image* _image; }; // Ellipse class MagickDLLDecl DrawableEllipse : public DrawableBase { public: DrawableEllipse ( double originX_, double originY_, double radiusX_, double radiusY_, double arcStart_, double arcEnd_ ) : _originX(originX_), _originY(originY_), _radiusX(radiusX_), _radiusY(radiusY_), _arcStart(arcStart_), _arcEnd(arcEnd_) { } /*virtual*/ ~DrawableEllipse( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void originX( double originX_ ) { _originX = originX_; } double originX( void ) const { return _originX; } void originY( double originY_ ) { _originY = originY_; } double originY( void ) const { return _originY; } void radiusX( double radiusX_ ) { _radiusX = radiusX_; } double radiusX( void ) const { return _radiusX; } void radiusY( double radiusY_ ) { _radiusY = radiusY_; } double radiusY( void ) const { return _radiusY; } void arcStart( double arcStart_ ) { _arcStart = arcStart_; } double arcStart( void ) const { return _arcStart; } void arcEnd( double arcEnd_ ) { _arcEnd = arcEnd_; } double arcEnd( void ) const { return _arcEnd; } private: double _originX; double _originY; double _radiusX; double _radiusY; double _arcStart; double _arcEnd; }; // Specify drawing fill color class MagickDLLDecl DrawableFillColor : public DrawableBase { public: DrawableFillColor ( const Color &color_ ); DrawableFillColor ( const DrawableFillColor& original_ ); /*virtual*/ ~DrawableFillColor( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void color( const Color &color_ ) { _color = color_; } Color color( void ) const { return _color; } private: Color _color; }; // Specify fill rule (fill-rule) class MagickDLLDecl DrawableFillRule : public DrawableBase { public: DrawableFillRule ( const FillRule fillRule_ ) : _fillRule(fillRule_) { } /*virtual*/ ~DrawableFillRule ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void fillRule( const FillRule fillRule_ ) { _fillRule = fillRule_; } FillRule fillRule( void ) const { return _fillRule; } private: FillRule _fillRule; }; // Specify drawing fill opacity class MagickDLLDecl DrawableFillOpacity : public DrawableBase { public: DrawableFillOpacity ( double opacity_ ) : _opacity(opacity_) { } /*virtual*/ ~DrawableFillOpacity ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void opacity( double opacity_ ) { _opacity = opacity_; } double opacity( void ) const { return _opacity; } private: double _opacity; }; // Specify text font class MagickDLLDecl DrawableFont : public DrawableBase { public: DrawableFont ( const std::string &font_ ); DrawableFont ( const std::string &family_, StyleType style_, const unsigned long weight_, StretchType stretch_ ); DrawableFont ( const DrawableFont& original_ ); /*virtual*/ ~DrawableFont ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void font( const std::string &font_ ) { _font = font_; } std::string font( void ) const { return _font; } private: std::string _font; std::string _family; StyleType _style; unsigned long _weight; StretchType _stretch; }; // Specify text positioning gravity class MagickDLLDecl DrawableGravity : public DrawableBase { public: DrawableGravity ( GravityType gravity_ ) : _gravity(gravity_) { } /*virtual*/ ~DrawableGravity ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void gravity( GravityType gravity_ ) { _gravity = gravity_; } GravityType gravity( void ) const { return _gravity; } private: GravityType _gravity; }; // Line class MagickDLLDecl DrawableLine : public DrawableBase { public: DrawableLine ( double startX_, double startY_, double endX_, double endY_ ) : _startX(startX_), _startY(startY_), _endX(endX_), _endY(endY_) { } /*virtual*/ ~DrawableLine ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void startX( double startX_ ) { _startX = startX_; } double startX( void ) const { return _startX; } void startY( double startY_ ) { _startY = startY_; } double startY( void ) const { return _startY; } void endX( double endX_ ) { _endX = endX_; } double endX( void ) const { return _endX; } void endY( double endY_ ) { _endY = endY_; } double endY( void ) const { return _endY; } private: double _startX; double _startY; double _endX; double _endY; }; // Change pixel matte value to transparent using PaintMethod class MagickDLLDecl DrawableMatte : public DrawableBase { public: DrawableMatte ( double x_, double y_, PaintMethod paintMethod_ ) : _x(x_), _y(y_), _paintMethod(paintMethod_) { } /*virtual*/ ~DrawableMatte ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } void paintMethod( PaintMethod paintMethod_ ) { _paintMethod = paintMethod_; } PaintMethod paintMethod( void ) const { return _paintMethod; } private: double _x; double _y; PaintMethod _paintMethod; }; // Drawable Path class MagickDLLDecl DrawablePath : public DrawableBase { public: DrawablePath ( const VPathList &path_ ); DrawablePath ( const DrawablePath& original_ ); /*virtual*/ ~DrawablePath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: VPathList _path; }; // Point class MagickDLLDecl DrawablePoint : public DrawableBase { public: DrawablePoint ( double x_, double y_ ) : _x(x_), _y(y_) { } /*virtual*/ ~DrawablePoint ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x; double _y; }; // Text pointsize class MagickDLLDecl DrawablePointSize : public DrawableBase { public: DrawablePointSize ( double pointSize_ ) : _pointSize(pointSize_) { } /*virtual*/ ~DrawablePointSize ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void pointSize( double pointSize_ ) { _pointSize = pointSize_; } double pointSize( void ) const { return _pointSize; } private: double _pointSize; }; // Polygon (Coordinate list must contain at least three members) class MagickDLLDecl DrawablePolygon : public DrawableBase { public: DrawablePolygon ( const CoordinateList &coordinates_ ); DrawablePolygon ( const DrawablePolygon& original_ ); /*virtual*/ ~DrawablePolygon ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: CoordinateList _coordinates; }; // Polyline (Coordinate list must contain at least three members) class MagickDLLDecl DrawablePolyline : public DrawableBase { public: DrawablePolyline ( const CoordinateList &coordinates_ ); DrawablePolyline ( const DrawablePolyline& original_ ); /*virtual*/ ~DrawablePolyline ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: CoordinateList _coordinates; }; // Pop Graphic Context class MagickDLLDecl DrawablePopGraphicContext : public DrawableBase { public: DrawablePopGraphicContext ( void ) : _dummy(0) { } /*virtual*/ ~DrawablePopGraphicContext ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: int _dummy; }; // Push Graphic Context class MagickDLLDecl DrawablePushGraphicContext : public DrawableBase { public: DrawablePushGraphicContext ( void ) : _dummy(0) { } /*virtual*/ ~DrawablePushGraphicContext ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: int _dummy; }; // Pop (terminate) Pattern definition class MagickDLLDecl DrawablePopPattern : public DrawableBase { public: DrawablePopPattern ( void ) : _dummy(0) { } /*virtual*/ ~DrawablePopPattern ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: int _dummy; }; // Push (create) Pattern definition class MagickDLLDecl DrawablePushPattern : public DrawableBase { public: DrawablePushPattern ( const std::string &id_, long x_, long y_, long width_, long height_ ); DrawablePushPattern ( const DrawablePushPattern& original_ ); /*virtual*/ ~DrawablePushPattern ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: std::string _id; long _x; long _y; long _width; long _height; }; // Rectangle class MagickDLLDecl DrawableRectangle : public DrawableBase { public: DrawableRectangle ( double upperLeftX_, double upperLeftY_, double lowerRightX_, double lowerRightY_ ) : _upperLeftX(upperLeftX_), _upperLeftY(upperLeftY_), _lowerRightX(lowerRightX_), _lowerRightY(lowerRightY_) { } /*virtual*/ ~DrawableRectangle ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void upperLeftX( double upperLeftX_ ) { _upperLeftX = upperLeftX_; } double upperLeftX( void ) const { return _upperLeftX; } void upperLeftY( double upperLeftY_ ) { _upperLeftY = upperLeftY_; } double upperLeftY( void ) const { return _upperLeftY; } void lowerRightX( double lowerRightX_ ) { _lowerRightX = lowerRightX_; } double lowerRightX( void ) const { return _lowerRightX; } void lowerRightY( double lowerRightY_ ) { _lowerRightY = lowerRightY_; } double lowerRightY( void ) const { return _lowerRightY; } private: double _upperLeftX; double _upperLeftY; double _lowerRightX; double _lowerRightY; }; // Apply Rotation class MagickDLLDecl DrawableRotation : public DrawableBase { public: DrawableRotation ( double angle_ ) : _angle( angle_ ) { } /*virtual*/ ~DrawableRotation ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void angle( double angle_ ) { _angle = angle_; } double angle( void ) const { return _angle; } private: double _angle; }; // Round Rectangle class MagickDLLDecl DrawableRoundRectangle : public DrawableBase { public: DrawableRoundRectangle ( double centerX_, double centerY_, double width_, double hight_, double cornerWidth_, double cornerHeight_ ) : _centerX(centerX_), _centerY(centerY_), _width(width_), _hight(hight_), _cornerWidth(cornerWidth_), _cornerHeight(cornerHeight_) { } /*virtual*/ ~DrawableRoundRectangle ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void centerX( double centerX_ ) { _centerX = centerX_; } double centerX( void ) const { return _centerX; } void centerY( double centerY_ ) { _centerY = centerY_; } double centerY( void ) const { return _centerY; } void width( double width_ ) { _width = width_; } double width( void ) const { return _width; } void hight( double hight_ ) { _hight = hight_; } double hight( void ) const { return _hight; } void cornerWidth( double cornerWidth_ ) { _cornerWidth = cornerWidth_; } double cornerWidth( void ) const { return _cornerWidth; } void cornerHeight( double cornerHeight_ ) { _cornerHeight = cornerHeight_; } double cornerHeight( void ) const { return _cornerHeight; } private: double _centerX; double _centerY; double _width; double _hight; double _cornerWidth; double _cornerHeight; }; // Apply Scaling class MagickDLLDecl DrawableScaling : public DrawableBase { public: DrawableScaling ( double x_, double y_ ) : _x(x_), _y(y_) { } /*virtual*/ ~DrawableScaling ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x; double _y; }; // Apply Skew in X direction class MagickDLLDecl DrawableSkewX : public DrawableBase { public: DrawableSkewX ( double angle_ ) : _angle(angle_) { } /*virtual*/ ~DrawableSkewX ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void angle( double angle_ ) { _angle = angle_; } double angle( void ) const { return _angle; } private: double _angle; }; // Apply Skew in Y direction class MagickDLLDecl DrawableSkewY : public DrawableBase { public: DrawableSkewY ( double angle_ ) : _angle(angle_) { } /*virtual*/ ~DrawableSkewY ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void angle( double angle_ ) { _angle = angle_; } double angle( void ) const { return _angle; } private: double _angle; }; // Stroke dasharray // // dasharray_ is an allocated array terminated by value 0.0 or 0. // The array is copied so the original does not need to be preserved. // Pass a null pointer to clear an existing dash array setting. class MagickDLLDecl DrawableDashArray : public DrawableBase { public: DrawableDashArray( const double* dasharray_ ); DrawableDashArray( const unsigned int* dasharray_ ); // Deprecated DrawableDashArray( const Magick::DrawableDashArray &original_ ); /*virtual*/ ~DrawableDashArray( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void dasharray( const double* dasharray_ ); void dasharray( const unsigned int* dasharray_ ); // Deprecated const double* dasharray( void ) const { return _dasharray; } DrawableDashArray& operator=(const Magick::DrawableDashArray &original_); private: size_t _size; double *_dasharray; }; // Stroke dashoffset class MagickDLLDecl DrawableDashOffset : public DrawableBase { public: DrawableDashOffset ( const double offset_ ) : _offset(offset_) { } /*virtual*/ ~DrawableDashOffset ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void offset( const double offset_ ) { _offset = offset_; } double offset( void ) const { return _offset; } private: double _offset; }; // Stroke linecap class MagickDLLDecl DrawableStrokeLineCap : public DrawableBase { public: DrawableStrokeLineCap ( LineCap linecap_ ) : _linecap(linecap_) { } /*virtual*/ ~DrawableStrokeLineCap ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void linecap( LineCap linecap_ ) { _linecap = linecap_; } LineCap linecap( void ) const { return _linecap; } private: LineCap _linecap; }; // Stroke linejoin class MagickDLLDecl DrawableStrokeLineJoin : public DrawableBase { public: DrawableStrokeLineJoin ( LineJoin linejoin_ ) : _linejoin(linejoin_) { } /*virtual*/ ~DrawableStrokeLineJoin ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void linejoin( LineJoin linejoin_ ) { _linejoin = linejoin_; } LineJoin linejoin( void ) const { return _linejoin; } private: LineJoin _linejoin; }; // Stroke miterlimit class MagickDLLDecl DrawableMiterLimit : public DrawableBase { public: DrawableMiterLimit ( unsigned int miterlimit_ ) : _miterlimit(miterlimit_) { } /*virtual*/ ~DrawableMiterLimit ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void miterlimit( unsigned int miterlimit_ ) { _miterlimit = miterlimit_; } unsigned int miterlimit( void ) const { return _miterlimit; } private: unsigned int _miterlimit; }; // Stroke antialias class MagickDLLDecl DrawableStrokeAntialias : public DrawableBase { public: DrawableStrokeAntialias ( bool flag_ ) : _flag(flag_) { } /*virtual*/ ~DrawableStrokeAntialias ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void flag( bool flag_ ) { _flag = flag_; } bool flag( void ) const { return _flag; } private: bool _flag; }; // Stroke color class MagickDLLDecl DrawableStrokeColor : public DrawableBase { public: DrawableStrokeColor ( const Color &color_ ); DrawableStrokeColor ( const DrawableStrokeColor& original_ ); /*virtual*/ ~DrawableStrokeColor ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void color( const Color& color_ ) { _color = color_; } Color color( void ) const { return _color; } private: Color _color; }; // Stroke opacity class MagickDLLDecl DrawableStrokeOpacity : public DrawableBase { public: DrawableStrokeOpacity ( double opacity_ ) : _opacity(opacity_) { } /*virtual*/ ~DrawableStrokeOpacity ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void opacity( double opacity_ ) { _opacity = opacity_; } double opacity( void ) const { return _opacity; } private: double _opacity; }; // Stroke width class MagickDLLDecl DrawableStrokeWidth : public DrawableBase { public: DrawableStrokeWidth ( double width_ ) : _width(width_) { } /*virtual*/ ~DrawableStrokeWidth ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void width( double width_ ) { _width = width_; } double width( void ) const { return _width; } private: double _width; }; // Draw text at point class MagickDLLDecl DrawableText : public DrawableBase { public: DrawableText ( const double x_, const double y_, const std::string &text_ ); DrawableText ( const double x_, const double y_, const std::string &text_, const std::string &encoding_); DrawableText ( const DrawableText& original_ ); /*virtual*/ ~DrawableText ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void encoding(const std::string &encoding_) { _encoding = encoding_; } void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } void text( const std::string &text_ ) { _text = text_; } std::string text( void ) const { return _text; } private: double _x; double _y; std::string _text; std::string _encoding; }; // Text antialias class MagickDLLDecl DrawableTextAntialias : public DrawableBase { public: DrawableTextAntialias ( bool flag_ ); DrawableTextAntialias( const DrawableTextAntialias &original_ ); /*virtual*/ ~DrawableTextAntialias ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void flag( bool flag_ ) { _flag = flag_; } bool flag( void ) const { return _flag; } private: bool _flag; }; // Decoration (text decoration) class MagickDLLDecl DrawableTextDecoration : public DrawableBase { public: DrawableTextDecoration ( DecorationType decoration_ ); DrawableTextDecoration ( const DrawableTextDecoration& original_ ); /*virtual*/ ~DrawableTextDecoration( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void decoration( DecorationType decoration_ ) { _decoration = decoration_; } DecorationType decoration( void ) const { return _decoration; } private: DecorationType _decoration; }; // Text undercolor box class MagickDLLDecl DrawableTextUnderColor : public DrawableBase { public: DrawableTextUnderColor ( const Color &color_ ); DrawableTextUnderColor ( const DrawableTextUnderColor& original_ ); /*virtual*/ ~DrawableTextUnderColor ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void color( const Color& color_ ) { _color = color_; } Color color( void ) const { return _color; } private: Color _color; }; // Apply Translation class MagickDLLDecl DrawableTranslation : public DrawableBase { public: DrawableTranslation ( double x_, double y_ ) : _x(x_), _y(y_) { } /*virtual*/ ~DrawableTranslation ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x; double _y; }; // Set the size of the viewbox class MagickDLLDecl DrawableViewbox : public DrawableBase { public: DrawableViewbox(unsigned long x1_, unsigned long y1_, unsigned long x2_, unsigned long y2_) : _x1(x1_), _y1(y1_), _x2(x2_), _y2(y2_) { } /*virtual*/ ~DrawableViewbox ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x1( unsigned long x1_ ) { _x1 = x1_; } unsigned long x1( void ) const { return _x1; } void y1( unsigned long y1_ ) { _y1 = y1_; } unsigned long y1( void ) const { return _y1; } void x2( unsigned long x2_ ) { _x2 = x2_; } unsigned long x2( void ) const { return _x2; } void y2( unsigned long y2_ ) { _y2 = y2_; } unsigned long y2( void ) const { return _y2; } private: unsigned long _x1; unsigned long _y1; unsigned long _x2; unsigned long _y2; }; // // Path Element Classes To Support DrawablePath // class MagickDLLDecl PathArcArgs { public: // Default constructor PathArcArgs( void ); // Path arc argument PathArcArgs( double radiusX_, double radiusY_, double xAxisRotation_, bool largeArcFlag_, bool sweepFlag_, double x_, double y_ ); PathArcArgs( const PathArcArgs &original_ ); ~PathArcArgs ( void ); void radiusX( double radiusX_ ) { _radiusX = radiusX_; } double radiusX( void ) const { return _radiusX; } void radiusY( double radiusY_ ) { _radiusY = radiusY_; } double radiusY( void ) const { return _radiusY; } void xAxisRotation( double xAxisRotation_ ) { _xAxisRotation = xAxisRotation_; } double xAxisRotation( void ) const { return _xAxisRotation; } void largeArcFlag( bool largeArcFlag_ ) { _largeArcFlag = largeArcFlag_; } bool largeArcFlag( void ) const { return _largeArcFlag; } void sweepFlag( bool sweepFlag_ ) { _sweepFlag = sweepFlag_; } bool sweepFlag( void ) const { return _sweepFlag; } void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _radiusX; // X radius double _radiusY; // Y radius double _xAxisRotation; // Rotation relative to X axis bool _largeArcFlag; // Draw longer of the two matching arcs bool _sweepFlag; // Draw arc matching clock-wise rotation double _x; // End-point X double _y; // End-point Y }; // Compare two PathArcArgs objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator != ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator > ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator < ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator >= ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator <= ( const PathArcArgs& left_, const PathArcArgs& right_ ); typedef std::list PathArcArgsList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate // Path Arc (Elliptical Arc) class MagickDLLDecl PathArcAbs : public VPathBase { public: // Draw a single arc segment PathArcAbs ( const PathArcArgs &coordinates_ ); // Draw multiple arc segments PathArcAbs ( const PathArcArgsList &coordinates_ ); // Copy constructor PathArcAbs ( const PathArcAbs& original_ ); // Destructor /*virtual*/ ~PathArcAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathArcArgsList _coordinates; }; class MagickDLLDecl PathArcRel : public VPathBase { public: // Draw a single arc segment PathArcRel ( const PathArcArgs &coordinates_ ); // Draw multiple arc segments PathArcRel ( const PathArcArgsList &coordinates_ ); PathArcRel ( const PathArcRel& original_ ); /*virtual*/ ~PathArcRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathArcArgsList _coordinates; }; // Path Closepath class MagickDLLDecl PathClosePath : public VPathBase { public: PathClosePath ( void ) : _dummy(0) { } /*virtual*/ ~PathClosePath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: int _dummy; }; // // Curveto (Cubic Bezier) // class MagickDLLDecl PathCurvetoArgs { public: PathCurvetoArgs( void ); PathCurvetoArgs( double x1_, double y1_, double x2_, double y2_, double x_, double y_ ); PathCurvetoArgs( const PathCurvetoArgs &original_ ); ~PathCurvetoArgs ( void ); void x1( double x1_ ) { _x1 = x1_; } double x1( void ) const { return _x1; } void y1( double y1_ ) { _y1 = y1_; } double y1( void ) const { return _y1; } void x2( double x2_ ) { _x2 = x2_; } double x2( void ) const { return _x2; } void y2( double y2_ ) { _y2 = y2_; } double y2( void ) const { return _y2; } void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x1; double _y1; double _x2; double _y2; double _x; double _y; }; // Compare two PathCurvetoArgs objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator != ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator > ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator < ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator >= ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator <= ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); typedef std::list PathCurveToArgsList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate class MagickDLLDecl PathCurvetoAbs : public VPathBase { public: // Draw a single curve PathCurvetoAbs ( const PathCurvetoArgs &args_ ); // Draw multiple curves PathCurvetoAbs ( const PathCurveToArgsList &args_ ); // Copy constructor PathCurvetoAbs ( const PathCurvetoAbs& original_ ); // Destructor /*virtual*/ ~PathCurvetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathCurveToArgsList _args; }; class MagickDLLDecl PathCurvetoRel : public VPathBase { public: // Draw a single curve PathCurvetoRel ( const PathCurvetoArgs &args_ ); // Draw multiple curves PathCurvetoRel ( const PathCurveToArgsList &args_ ); // Copy constructor PathCurvetoRel ( const PathCurvetoRel& original_ ); /*virtual*/ ~PathCurvetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathCurveToArgsList _args; }; class MagickDLLDecl PathSmoothCurvetoAbs : public VPathBase { public: // Draw a single curve PathSmoothCurvetoAbs ( const Magick::Coordinate &coordinates_ ); // Draw multiple curves PathSmoothCurvetoAbs ( const CoordinateList &coordinates_ ); // Copy constructor PathSmoothCurvetoAbs ( const PathSmoothCurvetoAbs& original_ ); /*virtual*/ ~PathSmoothCurvetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; class MagickDLLDecl PathSmoothCurvetoRel : public VPathBase { public: // Draw a single curve PathSmoothCurvetoRel ( const Coordinate &coordinates_ ); // Draw multiple curves PathSmoothCurvetoRel ( const CoordinateList &coordinates_ ); // Copy constructor PathSmoothCurvetoRel ( const PathSmoothCurvetoRel& original_ ); // Destructor /*virtual*/ ~PathSmoothCurvetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; // // Quadratic Curveto (Quadratic Bezier) // class MagickDLLDecl PathQuadraticCurvetoArgs { public: // Default constructor PathQuadraticCurvetoArgs( void ); // Parameterized constructor PathQuadraticCurvetoArgs( double x1_, double y1_, double x_, double y_ ); // Copy constructor PathQuadraticCurvetoArgs( const PathQuadraticCurvetoArgs &original_ ); ~PathQuadraticCurvetoArgs ( void ); void x1( double x1_ ) { _x1 = x1_; } double x1( void ) const { return _x1; } void y1( double y1_ ) { _y1 = y1_; } double y1( void ) const { return _y1; } void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x1; double _y1; double _x; double _y; }; // Compare two PathQuadraticCurvetoArgs objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_ ); MagickDLLDeclExtern int operator != ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_); MagickDLLDeclExtern int operator > ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_); MagickDLLDeclExtern int operator < ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_); MagickDLLDeclExtern int operator >= ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_ ); MagickDLLDeclExtern int operator <= ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_ ); typedef std::list PathQuadraticCurvetoArgsList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate class MagickDLLDecl PathQuadraticCurvetoAbs : public VPathBase { public: // Draw a single curve PathQuadraticCurvetoAbs ( const Magick::PathQuadraticCurvetoArgs &args_ ); // Draw multiple curves PathQuadraticCurvetoAbs ( const PathQuadraticCurvetoArgsList &args_ ); // Copy constructor PathQuadraticCurvetoAbs ( const PathQuadraticCurvetoAbs& original_ ); // Destructor /*virtual*/ ~PathQuadraticCurvetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathQuadraticCurvetoArgsList _args; }; class MagickDLLDecl PathQuadraticCurvetoRel : public VPathBase { public: // Draw a single curve PathQuadraticCurvetoRel ( const Magick::PathQuadraticCurvetoArgs &args_ ); // Draw multiple curves PathQuadraticCurvetoRel ( const PathQuadraticCurvetoArgsList &args_ ); // Copy constructor PathQuadraticCurvetoRel ( const PathQuadraticCurvetoRel& original_ ); // Destructor /*virtual*/ ~PathQuadraticCurvetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathQuadraticCurvetoArgsList _args; }; class MagickDLLDecl PathSmoothQuadraticCurvetoAbs : public VPathBase { public: // Draw a single curve PathSmoothQuadraticCurvetoAbs ( const Magick::Coordinate &coordinate_ ); // Draw multiple curves PathSmoothQuadraticCurvetoAbs ( const CoordinateList &coordinates_ ); // Copy constructor PathSmoothQuadraticCurvetoAbs ( const PathSmoothQuadraticCurvetoAbs& original_ ); // Destructor /*virtual*/ ~PathSmoothQuadraticCurvetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; class MagickDLLDecl PathSmoothQuadraticCurvetoRel : public VPathBase { public: // Draw a single curve PathSmoothQuadraticCurvetoRel ( const Magick::Coordinate &coordinate_ ); // Draw multiple curves PathSmoothQuadraticCurvetoRel ( const CoordinateList &coordinates_ ); // Copy constructor PathSmoothQuadraticCurvetoRel ( const PathSmoothQuadraticCurvetoRel& original_ ); // Destructor /*virtual*/ ~PathSmoothQuadraticCurvetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; // // Path Lineto // class MagickDLLDecl PathLinetoAbs : public VPathBase { public: // Draw to a single point PathLinetoAbs ( const Magick::Coordinate& coordinate_ ); // Draw to multiple points PathLinetoAbs ( const CoordinateList &coordinates_ ); // Copy constructor PathLinetoAbs ( const PathLinetoAbs& original_ ); // Destructor /*virtual*/ ~PathLinetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; class MagickDLLDecl PathLinetoRel : public VPathBase { public: // Draw to a single point PathLinetoRel ( const Magick::Coordinate& coordinate_ ); // Draw to multiple points PathLinetoRel ( const CoordinateList &coordinates_ ); // Copy constructor PathLinetoRel ( const PathLinetoRel& original_ ); // Destructor /*virtual*/ ~PathLinetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; // Path Horizontal Lineto class MagickDLLDecl PathLinetoHorizontalAbs : public VPathBase { public: PathLinetoHorizontalAbs ( double x_ ) : _x(x_) { } /*virtual*/ ~PathLinetoHorizontalAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } private: double _x; }; class MagickDLLDecl PathLinetoHorizontalRel : public VPathBase { public: PathLinetoHorizontalRel ( double x_ ) : _x(x_) { } /*virtual*/ ~PathLinetoHorizontalRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } private: double _x; }; // Path Vertical Lineto class MagickDLLDecl PathLinetoVerticalAbs : public VPathBase { public: PathLinetoVerticalAbs ( double y_ ) : _y(y_) { } /*virtual*/ ~PathLinetoVerticalAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _y; }; class MagickDLLDecl PathLinetoVerticalRel : public VPathBase { public: PathLinetoVerticalRel ( double y_ ) : _y(y_) { } /*virtual*/ ~PathLinetoVerticalRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _y; }; // Path Moveto class MagickDLLDecl PathMovetoAbs : public VPathBase { public: // Simple moveto PathMovetoAbs ( const Magick::Coordinate &coordinate_ ); // Moveto followed by implicit linetos PathMovetoAbs ( const CoordinateList &coordinates_ ); // Copy constructor PathMovetoAbs ( const PathMovetoAbs& original_ ); // Destructor /*virtual*/ ~PathMovetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; class MagickDLLDecl PathMovetoRel : public VPathBase { public: // Simple moveto PathMovetoRel ( const Magick::Coordinate &coordinate_ ); // Moveto followed by implicit linetos PathMovetoRel ( const CoordinateList &coordinates_ ); // Copy constructor PathMovetoRel ( const PathMovetoRel& original_ ); // Destructor /*virtual*/ ~PathMovetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; #if defined(__clang__) #pragma clang diagnostic pop #endif /* if defined(__clang__) */ } // namespace Magick #endif // Magick_Drawable_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Exception.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // // Definition of Magick::Exception and derived classes // Magick::Warning* and Magick::Error*. Derived from C++ STD // 'exception' class for convenience. // // These classes form part of the Magick++ user interface. // #if !defined(Magick_Exception_header) #define Magick_Exception_header #include "Magick++/Include.h" #include #include namespace Magick { class MagickDLLDecl Exception : public std::exception { public: Exception( const std::string& what_ ); Exception( const Exception& original_ ); Exception& operator= (const Exception& original_ ); virtual const char* what () const throw(); virtual ~Exception ( ) throw (); private: std::string _what; }; // // Warnings // class MagickDLLDecl Warning : public Exception { public: explicit Warning ( const std::string& what_ ); ~Warning() throw (); }; class MagickDLLDecl WarningUndefined : public Warning { public: explicit WarningUndefined ( const std::string& what_ ); ~WarningUndefined() throw (); }; class MagickDLLDecl WarningBlob: public Warning { public: explicit WarningBlob ( const std::string& what_ ); ~WarningBlob() throw (); }; class MagickDLLDecl WarningCache: public Warning { public: explicit WarningCache ( const std::string& what_ ); ~WarningCache() throw (); }; class MagickDLLDecl WarningCoder: public Warning { public: explicit WarningCoder ( const std::string& what_ ); ~WarningCoder() throw (); }; class MagickDLLDecl WarningConfigure: public Warning { public: explicit WarningConfigure ( const std::string& what_ ); ~WarningConfigure() throw (); }; class MagickDLLDecl WarningCorruptImage: public Warning { public: explicit WarningCorruptImage ( const std::string& what_ ); ~WarningCorruptImage() throw (); }; class MagickDLLDecl WarningDelegate : public Warning { public: explicit WarningDelegate ( const std::string& what_ ); ~WarningDelegate() throw (); }; class MagickDLLDecl WarningDraw : public Warning { public: explicit WarningDraw ( const std::string& what_ ); ~WarningDraw() throw (); }; class MagickDLLDecl WarningFileOpen: public Warning { public: explicit WarningFileOpen ( const std::string& what_ ); ~WarningFileOpen() throw (); }; class MagickDLLDecl WarningImage: public Warning { public: explicit WarningImage ( const std::string& what_ ); ~WarningImage() throw (); }; class MagickDLLDecl WarningMissingDelegate : public Warning { public: explicit WarningMissingDelegate ( const std::string& what_ ); ~WarningMissingDelegate() throw (); }; class MagickDLLDecl WarningModule : public Warning { public: explicit WarningModule ( const std::string& what_ ); ~WarningModule() throw (); }; class MagickDLLDecl WarningMonitor : public Warning { public: explicit WarningMonitor ( const std::string& what_ ); ~WarningMonitor() throw (); }; class MagickDLLDecl WarningOption : public Warning { public: explicit WarningOption ( const std::string& what_ ); ~WarningOption() throw (); }; class MagickDLLDecl WarningRegistry : public Warning { public: explicit WarningRegistry ( const std::string& what_ ); ~WarningRegistry() throw (); }; class MagickDLLDecl WarningResourceLimit : public Warning { public: explicit WarningResourceLimit ( const std::string& what_ ); ~WarningResourceLimit() throw (); }; class MagickDLLDecl WarningStream : public Warning { public: explicit WarningStream ( const std::string& what_ ); ~WarningStream() throw (); }; class MagickDLLDecl WarningType : public Warning { public: explicit WarningType ( const std::string& what_ ); ~WarningType() throw (); }; class MagickDLLDecl WarningXServer : public Warning { public: explicit WarningXServer ( const std::string& what_ ); ~WarningXServer() throw (); }; // // Error exceptions // class MagickDLLDecl Error : public Exception { public: explicit Error ( const std::string& what_ ); ~Error() throw (); }; class MagickDLLDecl ErrorUndefined : public Error { public: explicit ErrorUndefined ( const std::string& what_ ); ~ErrorUndefined() throw (); }; class MagickDLLDecl ErrorBlob: public Error { public: explicit ErrorBlob ( const std::string& what_ ); ~ErrorBlob() throw (); }; class MagickDLLDecl ErrorCache: public Error { public: explicit ErrorCache ( const std::string& what_ ); ~ErrorCache() throw (); }; class MagickDLLDecl ErrorCoder: public Error { public: explicit ErrorCoder ( const std::string& what_ ); ~ErrorCoder() throw (); }; class MagickDLLDecl ErrorConfigure: public Error { public: explicit ErrorConfigure ( const std::string& what_ ); ~ErrorConfigure() throw (); }; class MagickDLLDecl ErrorCorruptImage: public Error { public: explicit ErrorCorruptImage ( const std::string& what_ ); ~ErrorCorruptImage() throw (); }; class MagickDLLDecl ErrorDelegate : public Error { public: explicit ErrorDelegate ( const std::string& what_ ); ~ErrorDelegate() throw (); }; class MagickDLLDecl ErrorDraw : public Error { public: explicit ErrorDraw ( const std::string& what_ ); ~ErrorDraw() throw (); }; class MagickDLLDecl ErrorFileOpen: public Error { public: explicit ErrorFileOpen ( const std::string& what_ ); ~ErrorFileOpen() throw (); }; class MagickDLLDecl ErrorImage: public Error { public: explicit ErrorImage ( const std::string& what_ ); ~ErrorImage() throw (); }; class MagickDLLDecl ErrorMissingDelegate : public Error { public: explicit ErrorMissingDelegate ( const std::string& what_ ); ~ErrorMissingDelegate() throw (); }; class MagickDLLDecl ErrorModule : public Error { public: explicit ErrorModule ( const std::string& what_ ); ~ErrorModule() throw (); }; class MagickDLLDecl ErrorMonitor : public Error { public: explicit ErrorMonitor ( const std::string& what_ ); ~ErrorMonitor() throw (); }; class MagickDLLDecl ErrorOption : public Error { public: explicit ErrorOption ( const std::string& what_ ); ~ErrorOption() throw (); }; class MagickDLLDecl ErrorRegistry : public Error { public: explicit ErrorRegistry ( const std::string& what_ ); ~ErrorRegistry() throw (); }; class MagickDLLDecl ErrorResourceLimit : public Error { public: explicit ErrorResourceLimit ( const std::string& what_ ); ~ErrorResourceLimit() throw (); }; class MagickDLLDecl ErrorStream : public Error { public: explicit ErrorStream ( const std::string& what_ ); ~ErrorStream() throw (); }; class MagickDLLDecl ErrorType : public Error { public: explicit ErrorType ( const std::string& what_ ); ~ErrorType() throw (); }; class MagickDLLDecl ErrorXServer : public Error { public: explicit ErrorXServer ( const std::string& what_ ); ~ErrorXServer() throw (); }; // // No user-serviceable components beyond this point. // // Throw exception based on raw data MagickDLLDeclExtern void throwExceptionExplicit( const MagickLib::ExceptionType severity_, const char* reason_, const char* description_ = 0 ); // Thow exception based on ImageMagick's ExceptionInfo MagickDLLDeclExtern void throwException( MagickLib::ExceptionInfo &exception_, const bool quiet_ = false ); } // namespace Magick #endif // Magick_Exception_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Geometry.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2014 // // Geometry Definition // // Representation of an ImageMagick geometry specification // X11 geometry specification plus hints #if !defined (Magick_Geometry_header) #define Magick_Geometry_header #include "Magick++/Include.h" #include namespace Magick { class MagickDLLDecl Geometry; // Compare two Geometry objects regardless of LHS/RHS int MagickDLLDecl operator == ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator != ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator > ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator < ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator >= ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator <= ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); class MagickDLLDecl Geometry { public: Geometry ( unsigned int width_, unsigned int height_, unsigned int xOff_ = 0, unsigned int yOff_ = 0, bool xNegative_ = false, bool yNegative_ = false ); Geometry ( const std::string &geometry_ ); Geometry ( const char * geometry_ ); Geometry ( const Geometry &geometry_ ); Geometry ( ); ~Geometry ( void ); // Width void width ( unsigned int width_ ); unsigned int width ( void ) const; // Height void height ( unsigned int height_ ); unsigned int height ( void ) const; // X offset from origin void xOff ( unsigned int xOff_ ); unsigned int xOff ( void ) const; // Y offset from origin void yOff ( unsigned int yOff_ ); unsigned int yOff ( void ) const; // Sign of X offset negative? (X origin at right) void xNegative ( bool xNegative_ ); bool xNegative ( void ) const; // Sign of Y offset negative? (Y origin at bottom) void yNegative ( bool yNegative_ ); bool yNegative ( void ) const; // Width and height are expressed as percentages void percent ( bool percent_ ); bool percent ( void ) const; // Resize without preserving aspect ratio (!) void aspect ( bool aspect_ ); bool aspect ( void ) const; // Resize if image is greater than size (>) void greater ( bool greater_ ); bool greater ( void ) const; // Resize if image is less than size (<) void less ( bool less_ ); bool less ( void ) const; // Resize image to fit total pixel area specified by dimensions (@). void limitPixels ( bool limitPixels_ ); bool limitPixels ( void ) const; // Dimensions are treated as minimum rather than maximum values (^) void fillArea ( bool fillArea_ ); bool fillArea ( void ) const; // Does object contain valid geometry? void isValid ( bool isValid_ ); bool isValid ( void ) const; // Set via geometry string const Geometry& operator = ( const std::string &geometry_ ); const Geometry& operator = ( const char * geometry_ ); // Assignment operator Geometry& operator= ( const Geometry& Geometry_ ); // Return geometry string operator std::string() const; // // Public methods below this point are for Magick++ use only. // // Construct from RectangleInfo Geometry ( const MagickLib::RectangleInfo &rectangle_ ); // Return an ImageMagick RectangleInfo struct operator MagickLib::RectangleInfo() const; private: unsigned int _width; unsigned int _height; unsigned int _xOff; unsigned int _yOff; union { struct { // Bit-field for compact boolean storage bool _xNegative : 1; bool _yNegative : 1; bool _isValid : 1; bool _percent : 1; // Interpret width & height as percentages (%) bool _aspect : 1; // Force exact size (!) bool _greater : 1; // Re-size only if larger than geometry (>) bool _less : 1; // Re-size only if smaller than geometry (<) bool _limitPixels : 1;// Resize image to fit total pixel area (@). bool _fillArea : 1; // Dimensions are treated as // minimum rather than maximum // values (^) } _b; struct { // Padding for future use. unsigned int pad[2]; } _padding; } _flags; // union }; // class Geometry; } // namespace Magick // // Inlines // #endif // Magick_Geometry_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Image.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2017 // // Definition of Image, the representation of a single image in Magick++ // #if !defined(Magick_Image_header) #define Magick_Image_header #include "Magick++/Include.h" #include #include #include "Magick++/Blob.h" #include "Magick++/Color.h" #include "Magick++/Drawable.h" #include "Magick++/Exception.h" #include "Magick++/Geometry.h" #include "Magick++/TypeMetric.h" namespace Magick { // Forward declarations class Options; class ImageRef; // extern MagickDLLDecl const std::string borderGeometryDefault; // extern MagickDLLDecl const std::string frameGeometryDefault; // extern MagickDLLDecl const std::string raiseGeometryDefault; extern MagickDLLDecl const char *borderGeometryDefault; extern MagickDLLDecl const char *frameGeometryDefault; extern MagickDLLDecl const char *raiseGeometryDefault; // Compare two Image objects regardless of LHS/RHS // Image sizes and signatures are used as basis of comparison int MagickDLLDecl operator == ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator != ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator > ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator < ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator >= ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator <= ( const Magick::Image& left_, const Magick::Image& right_ ); // C library initialization routine void MagickDLLDecl InitializeMagick(const char *path_); // // Image is the representation of an image. In reality, it actually // a handle object which contains a pointer to a shared reference // object (ImageRef). As such, this object is extremely space efficient. // class MagickDLLDecl Image { public: // Construct from image file or image specification Image( const std::string &imageSpec_ ); // Construct a blank image canvas of specified size and color Image( const Geometry &size_, const Color &color_ ); // Construct Image from in-memory BLOB Image ( const Blob &blob_ ); // Construct Image of specified size from in-memory BLOB Image ( const Blob &blob_, const Geometry &size_ ); // Construct Image of specified size and depth from in-memory BLOB Image ( const Blob &blob_, const Geometry &size, const unsigned int depth ); // Construct Image of specified size, depth, and format from // in-memory BLOB Image ( const Blob &blob_, const Geometry &size, const unsigned int depth_, const std::string &magick_ ); // Construct Image of specified size, and format from in-memory // BLOB Image ( const Blob &blob_, const Geometry &size, const std::string &magick_ ); // Construct an image based on an array of raw pixels, of // specified type and mapping, in memory Image ( const unsigned int width_, const unsigned int height_, const std::string &map_, const StorageType type_, const void *pixels_ ); // Default constructor Image( void ); // Destructor virtual ~Image(); /// Copy constructor Image ( const Image & image_ ); // Assignment operator Image& operator= ( const Image &image_ ); ////////////////////////////////////////////////////////////////////// // // Image operations // ////////////////////////////////////////////////////////////////////// // Local adaptive threshold image // http://www.dai.ed.ac.uk/HIPR2/adpthrsh.htm // Width x height define the size of the pixel neighborhood // offset = constant to subtract from pixel neighborhood mean void adaptiveThreshold ( const unsigned int width, const unsigned int height, const double offset = 0.0 ); void adaptiveThreshold ( const unsigned int width, const unsigned int height, const unsigned int offset) MAGICK_FUNC_DEPRECATED; // Add noise to image with specified noise type void addNoise ( const NoiseType noiseType_ ); void addNoiseChannel ( const ChannelType channel_, const NoiseType noiseType_); // Transform image by specified affine (or free transform) matrix. void affineTransform ( const DrawableAffine &affine ); // // Annotate image (draw text on image) // // Gravity effects text placement in bounding area according to rules: // NorthWestGravity text bottom-left corner placed at top-left // NorthGravity text bottom-center placed at top-center // NorthEastGravity text bottom-right corner placed at top-right // WestGravity text left-center placed at left-center // CenterGravity text center placed at center // EastGravity text right-center placed at right-center // SouthWestGravity text top-left placed at bottom-left // SouthGravity text top-center placed at bottom-center // SouthEastGravity text top-right placed at bottom-right // Annotate using specified text, and placement location void annotate ( const std::string &text_, const Geometry &location_ ); // Annotate using specified text, bounding area, and placement // gravity void annotate ( const std::string &text_, const Geometry &boundingArea_, const GravityType gravity_ ); // Annotate with text using specified text, bounding area, // placement gravity, and rotation. void annotate ( const std::string &text_, const Geometry &boundingArea_, const GravityType gravity_, const double degrees_ ); // Annotate with text (bounding area is entire image) and placement // gravity. void annotate ( const std::string &text_, const GravityType gravity_ ); // Orient image to be right-side up based on its current // orientation attribute. This allows the image to be viewed // correctly when the orientation attribute is not available, or // is not respected. void autoOrient( void ); // Blur image with specified blur factor // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. void blur ( const double radius_ = 0.0, const double sigma_ = 1.0 ); void blurChannel ( const ChannelType channel_, const double radius_ = 0.0, const double sigma_ = 1.0 ); // Border image (add border to image) void border ( const Geometry &geometry_ = borderGeometryDefault ); // Bake in the ASC-CDL, which is a convention for the for the // exchange of basic primary color grading information between for // the exchange of basic primary color grading information between // equipment and software from different manufacturers. It is a // useful transform for other purposes as well. void cdl ( const std::string &cdl_ ); // Extract channel from image void channel ( const ChannelType channel_ ); // Set or obtain modulus channel depth void channelDepth ( const ChannelType channel_, const unsigned int depth_ ); unsigned int channelDepth ( const ChannelType channel_ ); // Charcoal effect image (looks like charcoal sketch) // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. void charcoal ( const double radius_ = 0.0, const double sigma_ = 1.0 ); // Chop image (remove vertical or horizontal subregion of image) // FIXME: describe how geometry argument is used to select either // horizontal or vertical subregion of image. void chop ( const Geometry &geometry_ ); // Colorize image with pen color, using specified percent opacity // for red, green, and blue quantums void colorize ( const unsigned int opacityRed_, const unsigned int opacityGreen_, const unsigned int opacityBlue_, const Color &penColor_ ); // Colorize image with pen color, using specified percent opacity. void colorize ( const unsigned int opacity_, const Color &penColor_ ); // Apply a color matrix to the image channels. The user supplied // matrix may be of order 1 to 5 (1x1 through 5x5). void colorMatrix (const unsigned int order_, const double *color_matrix_); // Comment image (add comment string to image) void comment ( const std::string &comment_ ); // Compare current image with another image // Sets meanErrorPerPixel, normalizedMaxError, and normalizedMeanError // in the current image. False is returned if the images are identical. bool compare ( const Image &reference_ ); // Compose an image onto another at specified offset and using // specified algorithm void composite ( const Image &compositeImage_, const int xOffset_, const int yOffset_, const CompositeOperator compose_ = InCompositeOp ); void composite ( const Image &compositeImage_, const Geometry &offset_, const CompositeOperator compose_ = InCompositeOp ); void composite ( const Image &compositeImage_, const GravityType gravity_, const CompositeOperator compose_ = InCompositeOp ); // Contrast image (enhance intensity differences in image) void contrast ( const unsigned int sharpen_ ); // Convolve image. Applies a user-specified convolution to the image. // order_ represents the number of columns and rows in the filter kernel. // kernel_ is an array of doubles representing the convolution kernel. void convolve ( const unsigned int order_, const double *kernel_ ); // Crop image (subregion of original image) void crop ( const Geometry &geometry_ ); // Cycle image colormap void cycleColormap ( const int amount_ ); // Despeckle image (reduce speckle noise) void despeckle ( void ); // Display image on screen void display ( void ); // Draw on image using a single drawable void draw ( const Drawable &drawable_ ); // Draw on image using a drawable list void draw ( const std::list &drawable_ ); // Edge image (hilight edges in image) void edge ( const double radius_ = 0.0 ); // Emboss image (hilight edges with 3D effect) // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. void emboss ( const double radius_ = 0.0, const double sigma_ = 1.0); // Enhance image (minimize noise) void enhance ( void ); // Equalize image (histogram equalization) void equalize ( void ); // Erase image to current "background color" void erase ( void ); // Create an image canvas using background color sized according // to geometry and composite existing image on it, with image // placement controlled by gravity. Parameters are obtained from // existing image properties if they are not specified via a // method parameter. Parameters which are supported by image // properties (gravity and backgroundColor) update those image // properties as a side-effect. void extent ( const Geometry &geometry_ ); void extent ( const Geometry &geometry_, const GravityType &gravity_ ); void extent ( const Geometry &geometry_, const Color &backgroundColor_ ); void extent ( const Geometry &geometry_, const Color &backgroundColor_, const GravityType &gravity_ ); // Flip image (reflect each scanline in the vertical direction) void flip ( void ); // Flood-fill color across pixels that match the color of the // target pixel and are neighbors of the target pixel. // Uses current fuzz setting when determining color match. void floodFillColor( const unsigned int x_, const unsigned int y_, const Color &fillColor_ ); void floodFillColor( const Geometry &point_, const Color &fillColor_ ); // Flood-fill color across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. void floodFillColor( const unsigned int x_, const unsigned int y_, const Color &fillColor_, const Color &borderColor_ ); void floodFillColor( const Geometry &point_, const Color &fillColor_, const Color &borderColor_ ); // Floodfill pixels matching color (within fuzz factor) of target // pixel(x,y) with replacement opacity value using method. void floodFillOpacity ( const unsigned int x_, const unsigned int y_, const unsigned int opacity_, const PaintMethod method_ ); // Flood-fill texture across pixels that match the color of the // target pixel and are neighbors of the target pixel. // Uses current fuzz setting when determining color match. void floodFillTexture( const unsigned int x_, const unsigned int y_, const Image &texture_ ); void floodFillTexture( const Geometry &point_, const Image &texture_ ); // Flood-fill texture across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. void floodFillTexture( const unsigned int x_, const unsigned int y_, const Image &texture_, const Color &borderColor_ ); void floodFillTexture( const Geometry &point_, const Image &texture_, const Color &borderColor_ ); // Flop image (reflect each scanline in the horizontal direction) void flop ( void ); // Frame image void frame ( const Geometry &geometry_ = frameGeometryDefault ); void frame ( const unsigned int width_, const unsigned int height_, const int innerBevel_ = 6, const int outerBevel_ = 6 ); // Gamma correct image void gamma ( const double gamma_ ); void gamma ( const double gammaRed_, const double gammaGreen_, const double gammaBlue_ ); // Gaussian blur image // The number of neighbor pixels to be included in the convolution // mask is specified by 'width_'. The standard deviation of the // gaussian bell curve is specified by 'sigma_'. void gaussianBlur ( const double width_, const double sigma_ ); void gaussianBlurChannel ( const ChannelType channel_, const double width_, const double sigma_ ); // Implode image (special effect) void implode ( const double factor_ ); // Apply a color lookup table (Hald CLUT) to the image. void haldClut ( const Image &clutImage_ ); // Label image void label ( const std::string &label_ ); // Level image. Adjust the levels of the image by scaling the // colors falling between specified white and black points to the // full available quantum range. The parameters provided represent // the black, mid (gamma), and white points. The black point // specifies the darkest color in the image. Colors darker than // the black point are set to zero. Mid point (gamma) specifies a // gamma correction to apply to the image. White point specifies // the lightest color in the image. Colors brighter than the // white point are set to the maximum quantum value. The black and // white point have the valid range 0 to MaxRGB while mid (gamma) // has a useful range of 0 to ten. void level ( const double black_point, const double white_point, const double mid_point=1.0 ); // Level image channel. Adjust the levels of the image channel by // scaling the values falling between specified white and black // points to the full available quantum range. The parameters // provided represent the black, mid (gamma), and white points. // The black point specifies the darkest color in the // image. Colors darker than the black point are set to zero. Mid // point (gamma) specifies a gamma correction to apply to the // image. White point specifies the lightest color in the image. // Colors brighter than the white point are set to the maximum // quantum value. The black and white point have the valid range 0 // to MaxRGB while mid (gamma) has a useful range of 0 to ten. void levelChannel ( const ChannelType channel, const double black_point, const double white_point, const double mid_point=1.0 ); // Magnify image by integral size void magnify ( void ); // Remap image colors with closest color from reference image void map ( const Image &mapImage_ , const bool dither_ = false ); // Floodfill designated area with replacement opacity value void matteFloodfill ( const Color &target_ , const unsigned int opacity_, const int x_, const int y_, const PaintMethod method_ ); // Filter image by replacing each pixel component with the median // color in a circular neighborhood void medianFilter ( const double radius_ = 0.0 ); // Reduce image by integral size void minify ( void ); // Modulate percent hue, saturation, and brightness of an image. // Modulation of saturation and brightness is as a ratio of the // current value (1.0 for no change). Modulation of hue is an // absolute rotation of -180 degrees to +180 degrees from the // current position corresponding to an argument range of 0 to 2.0 // (1.0 for no change). void modulate ( const double brightness_, const double saturation_, const double hue_ ); // Motion blur image with specified blur factor // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. // The angle_ parameter specifies the angle the object appears // to be comming from (zero degrees is from the right). void motionBlur ( const double radius_, const double sigma_, const double angle_ ); // Negate colors in image. Set grayscale to only negate grayscale // values in image. void negate ( const bool grayscale_ = false ); // Normalize image (increase contrast by normalizing the pixel // values to span the full range of color values) void normalize ( void ); // Oilpaint image (image looks like oil painting) void oilPaint ( const double radius_ = 3.0 ); // Set or attenuate the opacity channel in the image. If the image // pixels are opaque then they are set to the specified opacity // value, otherwise they are blended with the supplied opacity // value. The value of opacity_ ranges from 0 (completely opaque) // to MaxRGB. The defines OpaqueOpacity and TransparentOpacity are // available to specify completely opaque or completely // transparent, respectively. void opacity ( const unsigned int opacity_ ); // Change color of opaque pixel to specified pen color. void opaque ( const Color &opaqueColor_, const Color &penColor_ ); // Ping is similar to read except only enough of the image is read // to determine the image columns, rows, and filesize. Access the // columns(), rows(), and fileSize() attributes after invoking // ping. The image data is not valid after calling ping. void ping ( const std::string &imageSpec_ ); // Ping is similar to read except only enough of the image is read // to determine the image columns, rows, and filesize. Access the // columns(), rows(), and fileSize() attributes after invoking // ping. The image data is not valid after calling ping. void ping ( const Blob &blob_ ); // Quantize image (reduce number of colors) void quantize ( const bool measureError_ = false ); // Apply an arithmetic or bitwise operator to the image pixel quantums. void quantumOperator ( const ChannelType channel_, const QuantumOperator operator_, Quantum rvalue_) MAGICK_FUNC_DEPRECATED; void quantumOperator ( const ChannelType channel_, const QuantumOperator operator_, double rvalue_); void quantumOperator ( const int x_,const int y_, const unsigned int columns_, const unsigned int rows_, const ChannelType channel_, const QuantumOperator operator_, const Quantum rvalue_) MAGICK_FUNC_DEPRECATED; void quantumOperator ( const int x_,const int y_, const unsigned int columns_, const unsigned int rows_, const ChannelType channel_, const QuantumOperator operator_, const double rvalue_); // Execute a named process module using an argc/argv syntax similar to // that accepted by a C 'main' routine. An exception is thrown if the // requested process module doesn't exist, fails to load, or fails during // execution. void process ( std::string name_, const int argc_, char **argv_ ); // Raise image (lighten or darken the edges of an image to give a // 3-D raised or lowered effect) void raise ( const Geometry &geometry_ = raiseGeometryDefault, const bool raisedFlag_ = false ); // Random threshold image. // // Changes the value of individual pixels based on the intensity // of each pixel compared to a random threshold. The result is a // low-contrast, two color image. The thresholds_ argument is a // geometry containing LOWxHIGH thresholds. If the string // contains 2x2, 3x3, or 4x4, then an ordered dither of order 2, // 3, or 4 will be performed instead. If a channel_ argument is // specified then only the specified channel is altered. This is // a very fast alternative to 'quantize' based dithering. void randomThreshold( const Geometry &thresholds_ ); void randomThresholdChannel( const Geometry &thresholds_, const ChannelType channel_ ); // Read single image frame into current object void read ( const std::string &imageSpec_ ); // Read single image frame of specified size into current object void read ( const Geometry &size_, const std::string &imageSpec_ ); // Read single image frame from in-memory BLOB void read ( const Blob &blob_ ); // Read single image frame of specified size from in-memory BLOB void read ( const Blob &blob_, const Geometry &size_ ); // Read single image frame of specified size and depth from // in-memory BLOB void read ( const Blob &blob_, const Geometry &size_, const unsigned int depth_ ); // Read single image frame of specified size, depth, and format // from in-memory BLOB void read ( const Blob &blob_, const Geometry &size_, const unsigned int depth_, const std::string &magick_ ); // Read single image frame of specified size, and format from // in-memory BLOB void read ( const Blob &blob_, const Geometry &size_, const std::string &magick_ ); // Read single image frame from an array of raw pixels, with // specified storage type (ConstituteImage), e.g. // image.read( 640, 480, "RGB", 0, pixels ); void read ( const unsigned int width_, const unsigned int height_, const std::string &map_, const StorageType type_, const void *pixels_ ); // Reduce noise in image using a noise peak elimination filter void reduceNoise ( void ); void reduceNoise ( const double order_ ); // Resets the image page canvas and position. void repage(); // Resize image, specifying geometry, filter, and blur void resize ( const Geometry &geometry_, const FilterTypes filterType_, const double blur_ ); // Resize image, specifying geometry and filter, with blur using // Image default. void resize ( const Geometry &geometry_, const FilterTypes filterType_ ); // Resize image, specifying only geometry, with filter and blur // obtained from Image default. Same result as 'zoom' method. void resize ( const Geometry &geometry_ ); // Roll image (rolls image vertically and horizontally) by specified // number of columnms and rows) void roll ( const Geometry &roll_ ); void roll ( const unsigned int columns_, const unsigned int rows_ ); // Rotate image counter-clockwise by specified number of degrees. void rotate ( const double degrees_ ); // Resize image by using pixel sampling algorithm void sample ( const Geometry &geometry_ ); // Resize image by using simple ratio algorithm void scale ( const Geometry &geometry_ ); // Resize image using several algorithms to make smaller images // very quickly. void thumbnail ( const Geometry &geometry_ ); // Segment (coalesce similar image components) by analyzing the // histograms of the color components and identifying units that // are homogeneous with the fuzzy c-means technique. Also uses // QuantizeColorSpace and Verbose image attributes void segment ( const double clusterThreshold_ = 1.0, const double smoothingThreshold_ = 1.5 ); // Shade image using distant light source void shade ( const double azimuth_ = 30, const double elevation_ = 30, const bool colorShading_ = false ); // Sharpen pixels in image // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. void sharpen ( const double radius_ = 0.0, const double sigma_ = 1.0 ); void sharpenChannel ( const ChannelType channel_, const double radius_ = 0.0, const double sigma_ = 1.0 ); // Shave pixels from image edges. void shave ( const Geometry &geometry_ ); // Shear image (create parallelogram by sliding image by X or Y axis) void shear ( const double xShearAngle_, const double yShearAngle_ ); // Solarize image (similar to effect seen when exposing a // photographic film to light during the development process) void solarize ( const double factor_ = 50.0 ); // Spread pixels randomly within image by specified ammount void spread ( const unsigned int amount_ = 3 ); // Add a digital watermark to the image (based on second image) void stegano ( const Image &watermark_ ); // Create an image which appears in stereo when viewed with // red-blue glasses (Red image on left, blue on right) void stereo ( const Image &rightImage_ ); // Remove all profiles and text attributes from the image. void strip ( void ); // Swirl image (image pixels are rotated by degrees) void swirl ( const double degrees_ ); // Channel a texture on image background void texture ( const Image &texture_ ); // Threshold image channels (below threshold becomes black, above // threshold becomes white). // The range of the threshold parameter is 0 to MaxRGB. void threshold ( const double threshold_ ); // Transform image based on image and crop geometries // Crop geometry is optional void transform ( const Geometry &imageGeometry_ ); void transform ( const Geometry &imageGeometry_, const Geometry &cropGeometry_ ); // Add matte image to image, setting pixels matching color to // transparent void transparent ( const Color &color_ ); // Trim edges that are the background color from the image void trim ( void ); // Image representation type (also see type attribute) // Available types: // Bilevel Grayscale GrayscaleMatte // Palette PaletteMatte TrueColor // TrueColorMatte ColorSeparation ColorSeparationMatte void type ( const ImageType type_ ); // Replace image with a sharpened version of the original image // using the unsharp mask algorithm. // radius_ // the radius of the Gaussian, in pixels, not counting the // center pixel. // sigma_ // the standard deviation of the Gaussian, in pixels. // amount_ // the percentage of the difference between the original and // the blur image that is added back into the original. // threshold_ // the threshold in pixels needed to apply the diffence amount. void unsharpmask ( const double radius_, const double sigma_, const double amount_, const double threshold_ ); void unsharpmaskChannel ( const ChannelType channel_, const double radius_, const double sigma_, const double amount_, const double threshold_ ); // Map image pixels to a sine wave void wave ( const double amplitude_ = 25.0, const double wavelength_ = 150.0 ); // Write single image frame to a file void write ( const std::string &imageSpec_ ); // Write single image frame to in-memory BLOB, with optional // format and adjoin parameters. void write ( Blob *blob_ ); void write ( Blob *blob_, const std::string &magick_ ); void write ( Blob *blob_, const std::string &magick_, const unsigned int depth_ ); // Write single image frame to an array of pixels with storage // type specified by user (DispatchImage), e.g. // image.write( 0, 0, 640, 1, "RGB", 0, pixels ); void write ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_, const std::string& map_, const StorageType type_, void *pixels_ ); // Zoom image to specified size. void zoom ( const Geometry &geometry_ ); ////////////////////////////////////////////////////////////////////// // // Image Attributes and Options // ////////////////////////////////////////////////////////////////////// // Join images into a single multi-image file void adjoin ( const bool flag_ ); bool adjoin ( void ) const; // Anti-alias Postscript and TrueType fonts (default true) void antiAlias( const bool flag_ ); bool antiAlias( void ); // Time in 1/100ths of a second which must expire before // displaying the next image in an animated sequence. void animationDelay ( const unsigned int delay_ ); unsigned int animationDelay ( void ) const; // Number of iterations to loop an animation (e.g. Netscape loop // extension) for. void animationIterations ( const unsigned int iterations_ ); unsigned int animationIterations ( void ) const; // Access/Update a named image text attribute. Updates append the // provided to any existing attribute text. Pass NULL as the // value to remove an existing value or before a subsequent call // to add new text. void attribute ( const std::string name_, const char * value_ ); void attribute ( const std::string name_, const std::string value_ ); std::string attribute ( const std::string name_ ); // Image background color void backgroundColor ( const Color &color_ ); Color backgroundColor ( void ) const; // Name of texture image to tile onto the image background void backgroundTexture (const std::string &backgroundTexture_ ); std::string backgroundTexture ( void ) const; // Base image width (before transformations) unsigned int baseColumns ( void ) const; // Base image filename (before transformations) std::string baseFilename ( void ) const; // Base image height (before transformations) unsigned int baseRows ( void ) const; // Image border color void borderColor ( const Color &color_ ); Color borderColor ( void ) const; // Return smallest bounding box enclosing non-border pixels. The // current fuzz value is used when discriminating between pixels. // This is the crop bounding box used by crop(Geometry(0,0)); Geometry boundingBox ( void ) const; // Text bounding-box base color (default none) void boxColor ( const Color &boxColor_ ); Color boxColor ( void ) const; // Pixel cache threshold in megabytes. Once this memory threshold // is exceeded, all subsequent pixels cache operations are to/from // disk. This setting is shared by all Image objects. static void cacheThreshold ( const unsigned int threshold_ ); // Chromaticity blue primary point (e.g. x=0.15, y=0.06) void chromaBluePrimary ( const double x_, const double y_ ); void chromaBluePrimary ( double *x_, double *y_ ) const; // Chromaticity green primary point (e.g. x=0.3, y=0.6) void chromaGreenPrimary ( const double x_, const double y_ ); void chromaGreenPrimary ( double *x_, double *y_ ) const; // Chromaticity red primary point (e.g. x=0.64, y=0.33) void chromaRedPrimary ( const double x_, const double y_ ); void chromaRedPrimary ( double *x_, double *y_ ) const; // Chromaticity white point (e.g. x=0.3127, y=0.329) void chromaWhitePoint ( const double x_, const double y_ ); void chromaWhitePoint ( double *x_, double *y_ ) const; // Image class (DirectClass or PseudoClass) // NOTE: setting a DirectClass image to PseudoClass will result in // the loss of color information if the number of colors in the // image is greater than the maximum palette size (either 256 or // 65536 entries depending on the value of QuantumDepth when // ImageMagick was built). void classType ( const ClassType class_ ); ClassType classType ( void ) const; // Associate a clip mask with the image. The clip mask must be the // same dimensions as the image. Pass an invalid image to unset an // existing clip mask. void clipMask ( const Image & clipMask_ ); Image clipMask ( void ) const; // Colors within this distance are considered equal void colorFuzz ( const double fuzz_ ); double colorFuzz ( void ) const; // Color at colormap position index_ void colorMap ( const unsigned int index_, const Color &color_ ); Color colorMap ( const unsigned int index_ ) const; // Colormap size (number of colormap entries) void colorMapSize ( const unsigned int entries_ ); unsigned int colorMapSize ( void ); // Image Color Space void colorSpace( const ColorspaceType colorSpace_ ); ColorspaceType colorSpace ( void ) const; // Image width unsigned int columns ( void ) const; // Image comment std::string comment ( void ) const; // Composition operator to be used when composition is implicitly // used (such as for image flattening). void compose (const CompositeOperator compose_); CompositeOperator compose ( void ) const; // Compression type void compressType ( const CompressionType compressType_ ); CompressionType compressType ( void ) const; // Enable printing of debug messages from ImageMagick void debug ( const bool flag_ ); bool debug ( void ) const; // Tagged image format define (set/access coder-specific option) The // magick_ option specifies the coder the define applies to. The key_ // option provides the key specific to that coder. The value_ option // provides the value to set (if any). See the defineSet() method if the // key must be removed entirely. void defineValue ( const std::string &magick_, const std::string &key_, const std::string &value_ ); std::string defineValue ( const std::string &magick_, const std::string &key_ ) const; // Tagged image format define. Similar to the defineValue() method // except that passing the flag_ value 'true' creates a value-less // define with that format and key. Passing the flag_ value 'false' // removes any existing matching definition. The method returns 'true' // if a matching key exists, and 'false' if no matching key exists. void defineSet ( const std::string &magick_, const std::string &key_, bool flag_ ); bool defineSet ( const std::string &magick_, const std::string &key_ ) const; // Vertical and horizontal resolution in pixels of the image // // The resolution is expressed in resolution units as supported by // the resolutionUnits() method. // // Please note that the underlying resolution is floating point // and use of this method will result in rounding floating point // value to integer vaues. Use the xResolution() and // yResolution() methods when full accuracy is required. void density ( const Geometry &geomery_ ); Geometry density ( void ) const; // Image depth (bits allocated to red/green/blue components) void depth ( const unsigned int depth_ ); unsigned int depth ( void ) const; // Tile names from within an image montage std::string directory ( void ) const; // Endianness (little like Intel or big like SPARC) for image // formats which support endian-specific options. void endian ( const EndianType endian_ ); EndianType endian ( void ) const; // Image file name void fileName ( const std::string &fileName_ ); std::string fileName ( void ) const; // Number of bytes of the image on disk off_t fileSize ( void ) const; // Color to use when filling drawn objects void fillColor ( const Color &fillColor_ ); Color fillColor ( void ) const; // Rule to use when filling drawn objects void fillRule ( const FillRule &fillRule_ ); FillRule fillRule ( void ) const; // Pattern to use while filling drawn objects. void fillPattern ( const Image &fillPattern_ ); Image fillPattern ( void ) const; // Filter to use when resizing image using 'zoom' or 'resize'. void filterType ( const FilterTypes filterType_ ); FilterTypes filterType ( void ) const; // Text rendering font void font ( const std::string &font_ ); std::string font ( void ) const; // Font point size void fontPointsize ( const double pointSize_ ); double fontPointsize ( void ) const; // Obtain font metrics for text string given current font, // pointsize, and density settings. void fontTypeMetrics( const std::string &text_, TypeMetric *metrics ); // Long image format description std::string format ( void ) const; // Format the specified expression similar to command line '-format'. // For example "%wx%h" is converted to a string containing image // WIDTHxHEIGHT like "640x480". std::string formatExpression( const std::string expression ); // Gamma level of the image double gamma ( void ) const; // Preferred size of the image when encoding Geometry geometry ( void ) const; // GIF disposal method void gifDisposeMethod ( const unsigned int disposeMethod_ ); unsigned int gifDisposeMethod ( void ) const; // ICC color profile (BLOB) void iccColorProfile( const Blob &colorProfile_ ); Blob iccColorProfile( void ) const; // Type of interlacing to use void interlaceType ( const InterlaceType interlace_ ); InterlaceType interlaceType ( void ) const; // IPTC profile (BLOB) void iptcProfile( const Blob& iptcProfile_ ); Blob iptcProfile( void ) const; // Does object contain valid image? void isValid ( const bool isValid_ ); bool isValid ( void ) const; // Image label std::string label ( void ) const; // Stroke width for drawing vector objects (default one) // This method is now deprecated. Please use strokeWidth instead. void lineWidth ( const double lineWidth_ ); double lineWidth ( void ) const; // File type magick identifier (.e.g "GIF") void magick ( const std::string &magick_ ); std::string magick ( void ) const; // Image supports transparency (matte channel) void matte ( const bool matteFlag_ ); bool matte ( void ) const; // Transparent color void matteColor ( const Color &matteColor_ ); Color matteColor ( void ) const; // The mean error per pixel computed when an image is color reduced double meanErrorPerPixel ( void ) const; // Image modulus depth (minimum number of bits required to support // red/green/blue components without loss of accuracy) void modulusDepth ( const unsigned int modulusDepth_ ); unsigned int modulusDepth ( void ) const; // Tile size and offset within an image montage Geometry montageGeometry ( void ) const; // Transform image to black and white void monochrome ( const bool monochromeFlag_ ); bool monochrome ( void ) const; // The normalized max error per pixel computed when an image is // color reduced. double normalizedMaxError ( void ) const; // The normalized mean error per pixel computed when an image is // color reduced. double normalizedMeanError ( void ) const; // Image orientation void orientation ( const OrientationType orientation_ ); OrientationType orientation ( void ) const; // Preferred size and location of an image canvas. void page ( const Geometry &pageSize_ ); Geometry page ( void ) const; // Pen color (deprecated, don't use any more) void penColor ( const Color &penColor_ ); Color penColor ( void ) const; // Pen texture image (deprecated, don't use any more) void penTexture ( const Image &penTexture_ ); Image penTexture ( void ) const; // Get/set pixel color at location x & y. void pixelColor ( const unsigned int x_, const unsigned int y_, const Color &color_ ); Color pixelColor ( const unsigned int x_, const unsigned int y_ ) const; // Add or remove a named profile to/from the image. Remove the // profile by passing an empty Blob (e.g. Blob()). Valid names are // "*", "8BIM", "ICM", "IPTC", or a user/format-defined profile name. void profile( const std::string name_, const Blob &colorProfile_ ); // Retrieve a named profile from the image. Valid names are: // "8BIM", "8BIMTEXT", "APP1", "APP1JPEG", "ICC", "ICM", & "IPTC" // or an existing user/format-defined profile name. Blob profile( const std::string name_ ) const; // JPEG/MIFF/PNG compression level (default 75). void quality ( const unsigned int quality_ ); unsigned int quality ( void ) const; // Maximum number of colors to quantize to void quantizeColors ( const unsigned int colors_ ); unsigned int quantizeColors ( void ) const; // Colorspace to quantize in. void quantizeColorSpace ( const ColorspaceType colorSpace_ ); ColorspaceType quantizeColorSpace ( void ) const; // Dither image during quantization (default true). void quantizeDither ( const bool ditherFlag_ ); bool quantizeDither ( void ) const; // Quantization tree-depth void quantizeTreeDepth ( const unsigned int treeDepth_ ); unsigned int quantizeTreeDepth ( void ) const; // Suppress all warning messages. Error messages are still reported. void quiet ( const bool quiet_ ); bool quiet ( void ) const; // The type of rendering intent void renderingIntent ( const RenderingIntent renderingIntent_ ); RenderingIntent renderingIntent ( void ) const; // Units of image resolution void resolutionUnits ( const ResolutionType resolutionUnits_ ); ResolutionType resolutionUnits ( void ) const; // The number of pixel rows in the image unsigned int rows ( void ) const; // Image scene number void scene ( const unsigned int scene_ ); unsigned int scene ( void ) const; // Image signature. Set force_ to true in order to re-calculate // the signature regardless of whether the image data has been // modified. std::string signature ( const bool force_ = false ) const; // Width and height of a raw image void size ( const Geometry &geometry_ ); Geometry size ( void ) const; // Obtain image statistics. Statistics are normalized to the range // of 0.0 to 1.0 and are output to the specified ImageStatistics // structure. void statistics ( ImageStatistics *statistics ) const; // enabled/disable stroke anti-aliasing void strokeAntiAlias( const bool flag_ ); bool strokeAntiAlias( void ) const; // Color to use when drawing object outlines void strokeColor ( const Color &strokeColor_ ); Color strokeColor ( void ) const; // Specify the pattern of dashes and gaps used to stroke // paths. The strokeDashArray represents a zero-terminated array // of numbers that specify the lengths of alternating dashes and // gaps in pixels. If an odd number of values is provided, then // the list of values is repeated to yield an even number of // values. A typical strokeDashArray_ array might contain the // members 5 3 2 0, where the zero value indicates the end of the // pattern array. void strokeDashArray ( const double* strokeDashArray_ ); const double* strokeDashArray ( void ) const; // While drawing using a dash pattern, specify distance into the // dash pattern to start the dash (default 0). void strokeDashOffset ( const double strokeDashOffset_ ); double strokeDashOffset ( void ) const; // Specify the shape to be used at the end of open subpaths when // they are stroked. Values of LineCap are UndefinedCap, ButtCap, // RoundCap, and SquareCap. void strokeLineCap ( const LineCap lineCap_ ); LineCap strokeLineCap ( void ) const; // Specify the shape to be used at the corners of paths (or other // vector shapes) when they are stroked. Values of LineJoin are // UndefinedJoin, MiterJoin, RoundJoin, and BevelJoin. void strokeLineJoin ( const LineJoin lineJoin_ ); LineJoin strokeLineJoin ( void ) const; // Specify miter limit. When two line segments meet at a sharp // angle and miter joins have been specified for 'lineJoin', it is // possible for the miter to extend far beyond the thickness of // the line stroking the path. The miterLimit' imposes a limit on // the ratio of the miter length to the 'lineWidth'. The default // value of this parameter is 4. void strokeMiterLimit ( const unsigned int miterLimit_ ); unsigned int strokeMiterLimit ( void ) const; // Pattern image to use while stroking object outlines. void strokePattern ( const Image &strokePattern_ ); Image strokePattern ( void ) const; // Stroke width for drawing vector objects (default one) void strokeWidth ( const double strokeWidth_ ); double strokeWidth ( void ) const; // Subimage of an image sequence void subImage ( const unsigned int subImage_ ); unsigned int subImage ( void ) const; // Number of images relative to the base image void subRange ( const unsigned int subRange_ ); unsigned int subRange ( void ) const; // Annotation text encoding (e.g. "UTF-16") void textEncoding ( const std::string &encoding_ ); std::string textEncoding ( void ) const; // Tile name void tileName ( const std::string &tileName_ ); std::string tileName ( void ) const; // Number of colors in the image unsigned long totalColors ( void ); // Origin of coordinate system to use when annotating with text or drawing void transformOrigin ( const double x_,const double y_ ); // Rotation to use when annotating with text or drawing void transformRotation ( const double angle_ ); // Reset transformation parameters to default void transformReset ( void ); // Scale to use when annotating with text or drawing void transformScale ( const double sx_, const double sy_ ); // Skew to use in X axis when annotating with text or drawing void transformSkewX ( const double skewx_ ); // Skew to use in Y axis when annotating with text or drawing void transformSkewY ( const double skewy_ ); // Image representation type (also see type operation) // Available types: // Bilevel Grayscale GrayscaleMatte // Palette PaletteMatte TrueColor // TrueColorMatte ColorSeparation ColorSeparationMatte ImageType type ( void ) const; // Print detailed information about the image void verbose ( const bool verboseFlag_ ); bool verbose ( void ) const; // FlashPix viewing parameters void view ( const std::string &view_ ); std::string view ( void ) const; // X11 display to display to, obtain fonts from, or to capture // image from void x11Display ( const std::string &display_ ); std::string x11Display ( void ) const; // x resolution of the image void xResolution ( const double x_resolution ); double xResolution ( void ) const; // y resolution of the image void yResolution ( const double y_resolution ); double yResolution ( void ) const; ////////////////////////////////////////////////////////////////////// // // Low-level Pixel Access Routines // // Also see the Pixels class, which provides support for multiple // cache views. // ////////////////////////////////////////////////////////////////////// // Transfers read-only pixels from the image to the pixel cache as // defined by the specified region const PixelPacket* getConstPixels ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ) const; // Obtain mutable image pixel indexes (valid for PseudoClass images) IndexPacket* getIndexes ( void ); // Obtain immutable image pixel indexes (valid for PseudoClass images) const IndexPacket* getConstIndexes ( void ) const; // Transfers pixels from the image to the pixel cache as defined // by the specified region. Modified pixels may be subsequently // transferred back to the image via syncPixels. This method is // valid for DirectClass images. PixelPacket* getPixels ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ); // Allocates a pixel cache region to store image pixels as defined // by the region rectangle. This area is subsequently transferred // from the pixel cache to the image via syncPixels. PixelPacket* setPixels ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ); // Transfers the image cache pixels to the image. void syncPixels ( void ); // Transfers one or more pixel components from a buffer or file // into the image pixel cache of an image. // Used to support image decoders. void readPixels ( const QuantumType quantum_, const unsigned char *source_ ); // Transfers one or more pixel components from the image pixel // cache to a buffer or file. // Used to support image encoders. void writePixels ( const QuantumType quantum_, unsigned char *destination_ ); ////////////////////////////////////////////////////////////////////// // // No user-serviceable parts beyond this point // ////////////////////////////////////////////////////////////////////// // Construct with MagickLib::Image and default options Image ( MagickLib::Image* image_ ); // Retrieve Image* MagickLib::Image*& image( void ); const MagickLib::Image* constImage( void ) const; // Retrieve Options* Options* options( void ); const Options* constOptions( void ) const; // Retrieve ImageInfo* MagickLib::ImageInfo * imageInfo( void ); const MagickLib::ImageInfo * constImageInfo( void ) const; // Retrieve QuantizeInfo* MagickLib::QuantizeInfo * quantizeInfo( void ); const MagickLib::QuantizeInfo * constQuantizeInfo( void ) const; // Replace current image (reference counted) MagickLib::Image* replaceImage ( MagickLib::Image* replacement_ ); // Prepare to update image (copy if reference > 1) void modifyImage ( void ); // Test for ImageMagick error and throw exception if error void throwImageException( void ) const; // Register image with image registry or obtain registration id long registerId( void ); // Unregister image from image registry void unregisterId( void) ; private: void throwImageException( MagickLib::ExceptionInfo &exception_ ) const; ImageRef * _imgRef; }; } // end of namespace Magick // // Inlines // // // Image // // Reduce noise in image using a noise peak elimination filter inline void Magick::Image::reduceNoise ( void ) { reduceNoise( 3.0 ); } // Stroke width for drawing vector objects (default one) inline void Magick::Image::lineWidth ( const double lineWidth_ ) { strokeWidth( lineWidth_ ); } inline double Magick::Image::lineWidth ( void ) const { return strokeWidth( ); } // Get image storage class inline Magick::ClassType Magick::Image::classType ( void ) const { return static_cast(constImage()->storage_class); } // Get number of image columns inline unsigned int Magick::Image::columns ( void ) const { return constImage()->columns; } // Get number of image rows inline unsigned int Magick::Image::rows ( void ) const { return constImage()->rows; } #endif // Magick_Image_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Include.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2018 // // Inclusion of GraphicsMagick headers (with namespace magic) #ifndef Magick_Include_header #define Magick_Include_header #if !defined(_MAGICK_CONFIG_H) # define _MAGICK_CONFIG_H # if !defined(vms) && !defined(macintosh) # include "magick/magick_config.h" # else # include "magick_config.h" # endif # undef inline // Remove possible definition from config.h # undef class #endif #include #include #include #include #include /* POSIX 1990 header and declares size_t and ssize_t */ #if defined(__BORLANDC__) # include /* Borland C++ Builder 4.0 requirement */ #endif // defined(__BORLANDC__) // // Include GraphicsMagick headers into namespace "MagickLib". If // MAGICK_IMPLEMENTATION is defined, include GraphicsMagick development // headers. This scheme minimizes the possibility of conflict with // user code. // namespace MagickLib { #include #undef inline // Remove possible definition from config.h #undef class } // // Provide appropriate DLL imports/exports for Visual C++, // Borland C++Builder and MinGW builds. // #if (defined(WIN32) || defined(WIN64)) && !defined (__CYGWIN__) //&& !defined(__MINGW32__) # define MagickCplusPlusDLLSupported #endif #if defined(MagickCplusPlusDLLSupported) # if defined(_MT) && defined(_DLL) && !defined(_LIB) && !defined(STATIC_MAGICK) // // In a native Windows build, the following defines are used: // // _MT = Multithreaded // _DLL = Using code is part of a DLL // _LIB = Using code is being built as a library. // _MAGICKMOD_ = Build uses loadable modules (Magick++ does not care about this) // // In the case where GraphicsMagick is built as a static library but the // using code is dynamic, STATIC_MAGICK may be defined in the project to // override triggering dynamic library behavior. // # if defined(_VISUALC_) # define MagickDLLExplicitTemplate /* Explicit template instantiation in DLLs */ # pragma warning( disable: 4273 ) /* Disable the stupid dll linkage warnings */ # pragma warning( disable: 4251 ) # endif # if !defined(MAGICK_IMPLEMENTATION) # define MagickDLLDecl __declspec(dllimport) # define MagickDLLDeclExtern extern __declspec(dllimport) # if defined(_VISUALC_) # pragma message( "Magick++ lib DLL import" ) # endif # else # if defined(__BORLANDC__) || defined(__MINGW32__) # define MagickDLLDecl __declspec(dllexport) # define MagickDLLDeclExtern __declspec(dllexport) # if defined(__BORLANDC__) # pragma message( "BCBMagick++ lib DLL export" ) # endif # else # define MagickDLLDecl __declspec(dllexport) # define MagickDLLDeclExtern extern __declspec(dllexport) # endif # if defined(_VISUALC_) # pragma message( "Magick++ lib DLL export" ) # endif # endif # else # define MagickDLLDecl # define MagickDLLDeclExtern # if defined(_VISUALC_) # pragma message( "Magick++ lib static interface" ) # endif # if defined(_MSC_VER) && defined(STATIC_MAGICK) && !defined(NOAUTOLINK_MAGICK) # if defined(_DEBUG) # if defined(HasBZLIB) # pragma comment(lib, "CORE_DB_bzlib_.lib") # endif # pragma comment(lib, "CORE_DB_coders_.lib") # pragma comment(lib, "CORE_DB_filters_.lib") # if defined(HasJBIG) # pragma comment(lib, "CORE_DB_jbig_.lib") # endif # if defined(HasJP2) # pragma comment(lib, "CORE_DB_jp2_.lib") # endif # if defined(HasJPEG) # pragma comment(lib, "CORE_DB_jpeg_.lib") # endif # if defined(HasLCMS) # pragma comment(lib, "CORE_DB_lcms_.lib") # endif # if defined(HasXML) # pragma comment(lib, "CORE_DB_libxml_.lib") # endif # pragma comment(lib, "CORE_DB_magick_.lib") # pragma comment(lib, "CORE_DB_Magick++_.lib") # if defined(HasPNG) # pragma comment(lib, "CORE_DB_png_.lib") # endif # if defined(HasTIFF) # pragma comment(lib, "CORE_DB_tiff_.lib") # endif # if defined(HasTTF) # pragma comment(lib, "CORE_DB_ttf_.lib") # endif # pragma comment(lib, "CORE_DB_wand_.lib") # if defined(HasWEBP) # pragma comment(lib, "CORE_DB_webp_.lib") # endif # if defined(HasWMFlite) # pragma comment(lib, "CORE_DB_wmf_.lib") # endif # if defined(HasX11) # pragma comment(lib, "CORE_DB_xlib_.lib") # endif # if defined(HasZLIB) # pragma comment(lib, "CORE_DB_zlib_.lib") # endif # else # if defined(HasBZLIB) # pragma comment(lib, "CORE_RL_bzlib_.lib") # endif # pragma comment(lib, "CORE_RL_coders_.lib") # pragma comment(lib, "CORE_RL_filters_.lib") # if defined(HasJBIG) # pragma comment(lib, "CORE_RL_jbig_.lib") # endif # if defined(HasJP2) # pragma comment(lib, "CORE_RL_jp2_.lib") # endif # if defined(HasJPEG) # pragma comment(lib, "CORE_RL_jpeg_.lib") # endif # if defined(HasLCMS) # pragma comment(lib, "CORE_RL_lcms_.lib") # endif # if defined(HasXML) # pragma comment(lib, "CORE_RL_libxml_.lib") # endif # pragma comment(lib, "CORE_RL_magick_.lib") # pragma comment(lib, "CORE_RL_Magick++_.lib") # if defined(HasPNG) # pragma comment(lib, "CORE_RL_png_.lib") # endif # if defined(HasTIFF) # pragma comment(lib, "CORE_RL_tiff_.lib") # endif # if defined(HasTTF) # pragma comment(lib, "CORE_RL_ttf_.lib") # endif # pragma comment(lib, "CORE_RL_wand_.lib") # if defined(HasWEBP) # pragma comment(lib, "CORE_RL_webp_.lib") # endif # if defined(HasWMFlite) # pragma comment(lib, "CORE_RL_wmf_.lib") # endif # if defined(HasX11) # pragma comment(lib, "CORE_RL_xlib_.lib") # endif # if defined(HasZLIB) # pragma comment(lib, "CORE_RL_zlib_.lib") # endif # endif # if defined(_WIN32_WCE) # pragma comment(lib, "wsock32.lib") # else # pragma comment(lib, "ws2_32.lib") # endif # endif # endif #else # define MagickDLLDecl # define MagickDLLDeclExtern #endif #if (defined(WIN32) || defined(WIN64)) && defined(_VISUALC_) # pragma warning(disable : 4996) /* function deprecation warnings */ #endif #if defined(MAGICK_IMPLEMENTATION) namespace MagickLib { # include "magick/enum_strings.h" } #endif // // Import GraphicsMagick symbols and types which are used as part of the // Magick++ API definition into namespace "Magick". // namespace Magick { // The datatype for an RGB component using MagickLib::Quantum; // Image class types using MagickLib::ClassType; using MagickLib::UndefinedClass; using MagickLib::DirectClass; using MagickLib::PseudoClass; // Channel types using MagickLib::ChannelType; using MagickLib::UndefinedChannel; using MagickLib::RedChannel; using MagickLib::CyanChannel; using MagickLib::GreenChannel; using MagickLib::MagentaChannel; using MagickLib::BlueChannel; using MagickLib::YellowChannel; using MagickLib::OpacityChannel; using MagickLib::BlackChannel; using MagickLib::MatteChannel; using MagickLib::AllChannels; using MagickLib::GrayChannel; // Color-space types using MagickLib::ColorspaceType; using MagickLib::UndefinedColorspace; using MagickLib::RGBColorspace; using MagickLib::GRAYColorspace; using MagickLib::TransparentColorspace; using MagickLib::OHTAColorspace; using MagickLib::XYZColorspace; using MagickLib::YCbCrColorspace; using MagickLib::YCCColorspace; using MagickLib::YIQColorspace; using MagickLib::YPbPrColorspace; using MagickLib::YUVColorspace; using MagickLib::CMYKColorspace; using MagickLib::sRGBColorspace; using MagickLib::HSLColorspace; using MagickLib::HWBColorspace; using MagickLib::LABColorspace; using MagickLib::CineonLogRGBColorspace; using MagickLib::Rec601LumaColorspace; using MagickLib::Rec709LumaColorspace; using MagickLib::Rec709YCbCrColorspace; // Composition operations using MagickLib::AddCompositeOp; using MagickLib::AtopCompositeOp; using MagickLib::BumpmapCompositeOp; using MagickLib::ClearCompositeOp; using MagickLib::ColorizeCompositeOp; using MagickLib::CompositeOperator; using MagickLib::CopyBlueCompositeOp; using MagickLib::CopyCompositeOp; using MagickLib::CopyGreenCompositeOp; using MagickLib::CopyOpacityCompositeOp; using MagickLib::CopyRedCompositeOp; using MagickLib::DarkenCompositeOp; using MagickLib::DifferenceCompositeOp; using MagickLib::DisplaceCompositeOp; using MagickLib::DissolveCompositeOp; using MagickLib::HueCompositeOp; using MagickLib::InCompositeOp; using MagickLib::LightenCompositeOp; using MagickLib::LuminizeCompositeOp; using MagickLib::MinusCompositeOp; using MagickLib::ModulateCompositeOp; using MagickLib::MultiplyCompositeOp; using MagickLib::NoCompositeOp; using MagickLib::OutCompositeOp; using MagickLib::OverCompositeOp; using MagickLib::OverlayCompositeOp; using MagickLib::PlusCompositeOp; using MagickLib::SaturateCompositeOp; using MagickLib::ScreenCompositeOp; using MagickLib::SubtractCompositeOp; using MagickLib::ThresholdCompositeOp; using MagickLib::UndefinedCompositeOp; using MagickLib::XorCompositeOp; using MagickLib::CopyCyanCompositeOp; using MagickLib::CopyMagentaCompositeOp; using MagickLib::CopyYellowCompositeOp; using MagickLib::CopyBlackCompositeOp; using MagickLib::DivideCompositeOp; using MagickLib::HardLightCompositeOp; using MagickLib::ExclusionCompositeOp; using MagickLib::ColorDodgeCompositeOp; using MagickLib::ColorBurnCompositeOp; using MagickLib::SoftLightCompositeOp; using MagickLib::LinearBurnCompositeOp; using MagickLib::LinearDodgeCompositeOp; using MagickLib::LinearLightCompositeOp; using MagickLib::VividLightCompositeOp; using MagickLib::PinLightCompositeOp; using MagickLib::HardMixCompositeOp; // Compression algorithms using MagickLib::CompressionType; using MagickLib::UndefinedCompression; using MagickLib::NoCompression; using MagickLib::BZipCompression; using MagickLib::FaxCompression; using MagickLib::Group3Compression; using MagickLib::Group4Compression; using MagickLib::JPEGCompression; using MagickLib::LZWCompression; using MagickLib::RLECompression; using MagickLib::ZipCompression; using MagickLib::LZMACompression; using MagickLib::JPEG2000Compression; using MagickLib::JBIG1Compression; using MagickLib::JBIG2Compression; using MagickLib::ZSTDCompression; using MagickLib::WebPCompression; using MagickLib::DisposeType; using MagickLib::UndefinedDispose; using MagickLib::NoneDispose; using MagickLib::BackgroundDispose; using MagickLib::PreviousDispose; // Endian options using MagickLib::EndianType; using MagickLib::UndefinedEndian; using MagickLib::LSBEndian; using MagickLib::MSBEndian; using MagickLib::NativeEndian; // Exception types using MagickLib::ExceptionType; using MagickLib::UndefinedException; using MagickLib::EventException; using MagickLib::ExceptionEvent; using MagickLib::ResourceEvent; using MagickLib::ResourceLimitEvent; using MagickLib::TypeEvent; using MagickLib::AnnotateEvent; using MagickLib::OptionEvent; using MagickLib::DelegateEvent; using MagickLib::MissingDelegateEvent; using MagickLib::CorruptImageEvent; using MagickLib::FileOpenEvent; using MagickLib::BlobEvent; using MagickLib::StreamEvent; using MagickLib::CacheEvent; using MagickLib::CoderEvent; using MagickLib::ModuleEvent; using MagickLib::DrawEvent; using MagickLib::RenderEvent; using MagickLib::ImageEvent; using MagickLib::WandEvent; using MagickLib::TemporaryFileEvent; using MagickLib::TransformEvent; using MagickLib::XServerEvent; using MagickLib::X11Event; using MagickLib::UserEvent; using MagickLib::MonitorEvent; using MagickLib::LocaleEvent; using MagickLib::DeprecateEvent; using MagickLib::RegistryEvent; using MagickLib::ConfigureEvent; using MagickLib::WarningException; using MagickLib::ExceptionWarning; using MagickLib::ResourceWarning; using MagickLib::ResourceLimitWarning; using MagickLib::TypeWarning; using MagickLib::AnnotateWarning; using MagickLib::OptionWarning; using MagickLib::DelegateWarning; using MagickLib::MissingDelegateWarning; using MagickLib::CorruptImageWarning; using MagickLib::FileOpenWarning; using MagickLib::BlobWarning; using MagickLib::StreamWarning; using MagickLib::CacheWarning; using MagickLib::CoderWarning; using MagickLib::ModuleWarning; using MagickLib::DrawWarning; using MagickLib::RenderWarning; using MagickLib::ImageWarning; using MagickLib::WandWarning; using MagickLib::TemporaryFileWarning; using MagickLib::TransformWarning; using MagickLib::XServerWarning; using MagickLib::X11Warning; using MagickLib::UserWarning; using MagickLib::MonitorWarning; using MagickLib::LocaleWarning; using MagickLib::DeprecateWarning; using MagickLib::RegistryWarning; using MagickLib::ConfigureWarning; using MagickLib::ErrorException; using MagickLib::ExceptionError; using MagickLib::ResourceError; using MagickLib::ResourceLimitError; using MagickLib::TypeError; using MagickLib::AnnotateError; using MagickLib::OptionError; using MagickLib::DelegateError; using MagickLib::MissingDelegateError; using MagickLib::CorruptImageError; using MagickLib::FileOpenError; using MagickLib::BlobError; using MagickLib::StreamError; using MagickLib::CacheError; using MagickLib::CoderError; using MagickLib::ModuleError; using MagickLib::DrawError; using MagickLib::RenderError; using MagickLib::ImageError; using MagickLib::WandError; using MagickLib::TemporaryFileError; using MagickLib::TransformError; using MagickLib::XServerError; using MagickLib::X11Error; using MagickLib::UserError; using MagickLib::MonitorError; using MagickLib::LocaleError; using MagickLib::DeprecateError; using MagickLib::RegistryError; using MagickLib::ConfigureError; using MagickLib::FatalErrorException; using MagickLib::ExceptionFatalError; using MagickLib::ResourceFatalError; using MagickLib::ResourceLimitFatalError; using MagickLib::TypeFatalError; using MagickLib::AnnotateFatalError; using MagickLib::OptionFatalError; using MagickLib::DelegateFatalError; using MagickLib::MissingDelegateFatalError; using MagickLib::CorruptImageFatalError; using MagickLib::FileOpenFatalError; using MagickLib::BlobFatalError; using MagickLib::StreamFatalError; using MagickLib::CacheFatalError; using MagickLib::CoderFatalError; using MagickLib::ModuleFatalError; using MagickLib::DrawFatalError; using MagickLib::RenderFatalError; using MagickLib::ImageFatalError; using MagickLib::WandFatalError; using MagickLib::TemporaryFileFatalError; using MagickLib::TransformFatalError; using MagickLib::XServerFatalError; using MagickLib::X11FatalError; using MagickLib::UserFatalError; using MagickLib::MonitorFatalError; using MagickLib::LocaleFatalError; using MagickLib::DeprecateFatalError; using MagickLib::RegistryFatalError; using MagickLib::ConfigureFatalError; // Fill rules using MagickLib::FillRule; using MagickLib::UndefinedRule; using MagickLib::EvenOddRule; using MagickLib::NonZeroRule; // Filter types using MagickLib::FilterTypes; using MagickLib::UndefinedFilter; using MagickLib::PointFilter; using MagickLib::BoxFilter; using MagickLib::TriangleFilter; using MagickLib::HermiteFilter; using MagickLib::HanningFilter; using MagickLib::HammingFilter; using MagickLib::BlackmanFilter; using MagickLib::GaussianFilter; using MagickLib::QuadraticFilter; using MagickLib::CubicFilter; using MagickLib::CatromFilter; using MagickLib::MitchellFilter; using MagickLib::LanczosFilter; using MagickLib::BesselFilter; using MagickLib::SincFilter; // Bit gravity using MagickLib::GravityType; using MagickLib::ForgetGravity; using MagickLib::NorthWestGravity; using MagickLib::NorthGravity; using MagickLib::NorthEastGravity; using MagickLib::WestGravity; using MagickLib::CenterGravity; using MagickLib::EastGravity; using MagickLib::SouthWestGravity; using MagickLib::SouthGravity; using MagickLib::SouthEastGravity; using MagickLib::StaticGravity; // Image types using MagickLib::ImageType; using MagickLib::UndefinedType; using MagickLib::BilevelType; using MagickLib::GrayscaleType; using MagickLib::GrayscaleMatteType; using MagickLib::PaletteType; using MagickLib::PaletteMatteType; using MagickLib::TrueColorType; using MagickLib::TrueColorMatteType; using MagickLib::ColorSeparationType; using MagickLib::ColorSeparationMatteType; using MagickLib::OptimizeType; // Interlace types using MagickLib::InterlaceType; using MagickLib::UndefinedInterlace; using MagickLib::NoInterlace; using MagickLib::LineInterlace; using MagickLib::PlaneInterlace; using MagickLib::PartitionInterlace; // Line cap types using MagickLib::LineCap; using MagickLib::UndefinedCap; using MagickLib::ButtCap; using MagickLib::RoundCap; using MagickLib::SquareCap; // Line join types using MagickLib::LineJoin; using MagickLib::UndefinedJoin; using MagickLib::MiterJoin; using MagickLib::RoundJoin; using MagickLib::BevelJoin; // Noise types using MagickLib::NoiseType; using MagickLib::UniformNoise; using MagickLib::GaussianNoise; using MagickLib::MultiplicativeGaussianNoise; using MagickLib::ImpulseNoise; using MagickLib::LaplacianNoise; using MagickLib::PoissonNoise; using MagickLib::RandomNoise; // Orientation types using MagickLib::OrientationType; using MagickLib::UndefinedOrientation; using MagickLib::TopLeftOrientation; using MagickLib::TopRightOrientation; using MagickLib::BottomRightOrientation; using MagickLib::BottomLeftOrientation; using MagickLib::LeftTopOrientation; using MagickLib::RightTopOrientation; using MagickLib::RightBottomOrientation; using MagickLib::LeftBottomOrientation; // Paint methods using MagickLib::PaintMethod; using MagickLib::PointMethod; using MagickLib::ReplaceMethod; using MagickLib::FloodfillMethod; using MagickLib::FillToBorderMethod; using MagickLib::ResetMethod; // Arithmetic and bitwise operators using MagickLib::UndefinedQuantumOp; using MagickLib::AddQuantumOp; using MagickLib::AndQuantumOp; using MagickLib::AssignQuantumOp; using MagickLib::DivideQuantumOp; using MagickLib::LShiftQuantumOp; using MagickLib::MultiplyQuantumOp; using MagickLib::OrQuantumOp; using MagickLib::RShiftQuantumOp; using MagickLib::SubtractQuantumOp; using MagickLib::ThresholdQuantumOp; using MagickLib::ThresholdBlackQuantumOp; using MagickLib::ThresholdWhiteQuantumOp; using MagickLib::ThresholdBlackNegateQuantumOp; using MagickLib::ThresholdWhiteNegateQuantumOp; using MagickLib::XorQuantumOp; using MagickLib::NoiseGaussianQuantumOp; using MagickLib::NoiseImpulseQuantumOp; using MagickLib::NoiseLaplacianQuantumOp; using MagickLib::NoiseMultiplicativeQuantumOp; using MagickLib::NoisePoissonQuantumOp; using MagickLib::NoiseUniformQuantumOp; using MagickLib::NegateQuantumOp; using MagickLib::GammaQuantumOp; using MagickLib::DepthQuantumOp; using MagickLib::LogQuantumOp; using MagickLib::MaxQuantumOp; using MagickLib::MinQuantumOp; using MagickLib::PowQuantumOp; using MagickLib::QuantumOperator; // Preview types. Not currently used by Magick++ using MagickLib::PreviewType; using MagickLib::UndefinedPreview; using MagickLib::RotatePreview; using MagickLib::ShearPreview; using MagickLib::RollPreview; using MagickLib::HuePreview; using MagickLib::SaturationPreview; using MagickLib::BrightnessPreview; using MagickLib::GammaPreview; using MagickLib::SpiffPreview; using MagickLib::DullPreview; using MagickLib::GrayscalePreview; using MagickLib::QuantizePreview; using MagickLib::DespecklePreview; using MagickLib::ReduceNoisePreview; using MagickLib::AddNoisePreview; using MagickLib::SharpenPreview; using MagickLib::BlurPreview; using MagickLib::ThresholdPreview; using MagickLib::EdgeDetectPreview; using MagickLib::SpreadPreview; using MagickLib::SolarizePreview; using MagickLib::ShadePreview; using MagickLib::RaisePreview; using MagickLib::SegmentPreview; using MagickLib::SwirlPreview; using MagickLib::ImplodePreview; using MagickLib::WavePreview; using MagickLib::OilPaintPreview; using MagickLib::CharcoalDrawingPreview; using MagickLib::JPEGPreview; // Quantum types using MagickLib::QuantumType; using MagickLib::IndexQuantum; using MagickLib::GrayQuantum; using MagickLib::IndexAlphaQuantum; using MagickLib::GrayAlphaQuantum; using MagickLib::RedQuantum; using MagickLib::CyanQuantum; using MagickLib::GreenQuantum; using MagickLib::YellowQuantum; using MagickLib::BlueQuantum; using MagickLib::MagentaQuantum; using MagickLib::AlphaQuantum; using MagickLib::BlackQuantum; using MagickLib::RGBQuantum; using MagickLib::RGBAQuantum; using MagickLib::CMYKQuantum; using MagickLib::CIEYQuantum; using MagickLib::CIEXYZQuantum; // Quantum sample types using MagickLib::QuantumSampleType; using MagickLib::UndefinedQuantumSampleType; using MagickLib::UnsignedQuantumSampleType; using MagickLib::FloatQuantumSampleType; // Rendering intents using MagickLib::RenderingIntent; using MagickLib::UndefinedIntent; using MagickLib::SaturationIntent; using MagickLib::PerceptualIntent; using MagickLib::AbsoluteIntent; using MagickLib::RelativeIntent; // Resolution units using MagickLib::ResolutionType; using MagickLib::UndefinedResolution; using MagickLib::PixelsPerInchResolution; using MagickLib::PixelsPerCentimeterResolution; // PixelPacket structure using MagickLib::PixelPacket; // IndexPacket type using MagickLib::IndexPacket; // ImageStatistics type using MagickLib::ImageStatistics; // StorageType type using MagickLib::StorageType; using MagickLib::CharPixel; using MagickLib::ShortPixel; using MagickLib::IntegerPixel; using MagickLib::LongPixel; using MagickLib::FloatPixel; using MagickLib::DoublePixel; // StretchType type using MagickLib::StretchType; using MagickLib::NormalStretch; using MagickLib::UltraCondensedStretch; using MagickLib::ExtraCondensedStretch; using MagickLib::CondensedStretch; using MagickLib::SemiCondensedStretch; using MagickLib::SemiExpandedStretch; using MagickLib::ExpandedStretch; using MagickLib::ExtraExpandedStretch; using MagickLib::UltraExpandedStretch; using MagickLib::AnyStretch; // StyleType type using MagickLib::StyleType; using MagickLib::NormalStyle; using MagickLib::ItalicStyle; using MagickLib::ObliqueStyle; using MagickLib::AnyStyle; // Decoration types using MagickLib::DecorationType; using MagickLib::NoDecoration; using MagickLib::UnderlineDecoration; using MagickLib::OverlineDecoration; using MagickLib::LineThroughDecoration; // Resource types using MagickLib::ResourceType; using MagickLib::DiskResource; using MagickLib::FileResource; using MagickLib::MapResource; using MagickLib::MemoryResource; using MagickLib::PixelsResource; using MagickLib::ThreadsResource; using MagickLib::WidthResource; using MagickLib::HeightResource; // Virtual pixel methods using MagickLib::VirtualPixelMethod; using MagickLib::UndefinedVirtualPixelMethod; using MagickLib::ConstantVirtualPixelMethod; using MagickLib::EdgeVirtualPixelMethod; using MagickLib::MirrorVirtualPixelMethod; using MagickLib::TileVirtualPixelMethod; #if defined(MAGICK_IMPLEMENTATION) // // GraphicsMagick symbols used in implementation code // using MagickLib::AccessDefinition; using MagickLib::AccessImmutableIndexes; using MagickLib::AccessMutableIndexes; using MagickLib::AcquireCacheViewPixels; using MagickLib::AcquireImagePixels; using MagickLib::AdaptiveThresholdImage; using MagickLib::AddDefinition; using MagickLib::AddDefinitions; using MagickLib::AddNoiseImage; using MagickLib::AddNoiseImageChannel; using MagickLib::AffineMatrix; using MagickLib::AffineTransformImage; using MagickLib::AllocateImage; using MagickLib::AnnotateImage; using MagickLib::AreaValue; using MagickLib::AspectValue; using MagickLib::Base64Decode; using MagickLib::Base64Encode; using MagickLib::BlobError; using MagickLib::BlobFatalError; using MagickLib::BlobToImage; using MagickLib::BlobWarning; using MagickLib::BlurImage; using MagickLib::BlurImageChannel; using MagickLib::BorderImage; using MagickLib::CacheError; using MagickLib::CacheFatalError; using MagickLib::CacheWarning; using MagickLib::CdlImage; using MagickLib::ChannelImage; using MagickLib::CharcoalImage; using MagickLib::ChopImage; using MagickLib::CloneDrawInfo; using MagickLib::CloneImage; using MagickLib::CloneImageInfo; using MagickLib::CloneQuantizeInfo; using MagickLib::CloseCacheView; using MagickLib::CoderError; using MagickLib::CoderFatalError; using MagickLib::CoderWarning; using MagickLib::ColorFloodfillImage; using MagickLib::ColorizeImage; using MagickLib::ColorMatrixImage; using MagickLib::CompositeImage; using MagickLib::ConfigureError; using MagickLib::ConfigureFatalError; using MagickLib::ConfigureWarning; using MagickLib::ConstituteImage; using MagickLib::ContrastImage; using MagickLib::ConvolveImage; using MagickLib::CopyException; using MagickLib::CorruptImageError; using MagickLib::CorruptImageFatalError; using MagickLib::CorruptImageWarning; using MagickLib::CropImage; using MagickLib::CycleColormapImage; using MagickLib::DelegateError; using MagickLib::DelegateFatalError; using MagickLib::DelegateWarning; using MagickLib::DeleteMagickRegistry; using MagickLib::DespeckleImage; using MagickLib::DestroyDrawInfo; using MagickLib::DestroyExceptionInfo; using MagickLib::DestroyImageInfo; using MagickLib::DestroyImageList; using MagickLib::DestroyMagick; using MagickLib::DestroyQuantizeInfo; using MagickLib::DispatchImage; using MagickLib::DisplayImages; using MagickLib::DrawAffine; using MagickLib::DrawAllocateContext; using MagickLib::DrawAnnotation; using MagickLib::DrawArc; using MagickLib::DrawBezier; using MagickLib::DrawCircle; using MagickLib::DrawColor; using MagickLib::DrawComment; using MagickLib::DrawComposite; using MagickLib::DrawContext; using MagickLib::DrawDestroyContext; using MagickLib::DrawEllipse; using MagickLib::DrawError; using MagickLib::DrawFatalError; using MagickLib::DrawImage; using MagickLib::DrawInfo; using MagickLib::DrawLine; using MagickLib::DrawMatte; using MagickLib::DrawPathClose; using MagickLib::DrawPathCurveToAbsolute; using MagickLib::DrawPathCurveToQuadraticBezierAbsolute; using MagickLib::DrawPathCurveToQuadraticBezierRelative; using MagickLib::DrawPathCurveToQuadraticBezierSmoothAbsolute; using MagickLib::DrawPathCurveToQuadraticBezierSmoothRelative; using MagickLib::DrawPathCurveToRelative; using MagickLib::DrawPathCurveToSmoothAbsolute; using MagickLib::DrawPathCurveToSmoothRelative; using MagickLib::DrawPathEllipticArcAbsolute; using MagickLib::DrawPathEllipticArcRelative; using MagickLib::DrawPathFinish; using MagickLib::DrawPathLineToAbsolute; using MagickLib::DrawPathLineToHorizontalAbsolute; using MagickLib::DrawPathLineToHorizontalRelative; using MagickLib::DrawPathLineToRelative; using MagickLib::DrawPathLineToVerticalAbsolute; using MagickLib::DrawPathLineToVerticalRelative; using MagickLib::DrawPathMoveToAbsolute; using MagickLib::DrawPathMoveToRelative; using MagickLib::DrawPathStart; using MagickLib::DrawPoint; using MagickLib::DrawPolygon; using MagickLib::DrawPolyline; using MagickLib::DrawPopClipPath; using MagickLib::DrawPopDefs; using MagickLib::DrawPopGraphicContext; using MagickLib::DrawPopPattern; using MagickLib::DrawPushClipPath; using MagickLib::DrawPushDefs; using MagickLib::DrawPushGraphicContext; using MagickLib::DrawPushPattern; using MagickLib::DrawRectangle; using MagickLib::DrawRender; using MagickLib::DrawRotate; using MagickLib::DrawRoundRectangle; using MagickLib::DrawScale; using MagickLib::DrawSetClipPath; using MagickLib::DrawSetClipRule; using MagickLib::DrawSetClipUnits; using MagickLib::DrawSetFillColor; using MagickLib::DrawSetFillColorString; using MagickLib::DrawSetFillOpacity; using MagickLib::DrawSetFillPatternURL; using MagickLib::DrawSetFillRule; using MagickLib::DrawSetFont; using MagickLib::DrawSetFontFamily; using MagickLib::DrawSetFontSize; using MagickLib::DrawSetFontStretch; using MagickLib::DrawSetFontStyle; using MagickLib::DrawSetFontWeight; using MagickLib::DrawSetGravity; using MagickLib::DrawSetStrokeAntialias; using MagickLib::DrawSetStrokeColor; using MagickLib::DrawSetStrokeColorString; using MagickLib::DrawSetStrokeDashArray; using MagickLib::DrawSetStrokeDashOffset; using MagickLib::DrawSetStrokeLineCap; using MagickLib::DrawSetStrokeLineJoin; using MagickLib::DrawSetStrokeMiterLimit; using MagickLib::DrawSetStrokeOpacity; using MagickLib::DrawSetStrokePatternURL; using MagickLib::DrawSetStrokeWidth; using MagickLib::DrawSetTextAntialias; using MagickLib::DrawSetTextDecoration; using MagickLib::DrawSetTextEncoding; using MagickLib::DrawSetTextUnderColor; using MagickLib::DrawSetTextUnderColorString; using MagickLib::DrawSetViewbox; using MagickLib::DrawSkewX; using MagickLib::DrawSkewY; using MagickLib::DrawTranslate; using MagickLib::DrawWarning; using MagickLib::EdgeImage; using MagickLib::EmbossImage; using MagickLib::EnhanceImage; using MagickLib::EqualizeImage; using MagickLib::ExceptionInfo; using MagickLib::ExecuteModuleProcess; using MagickLib::ExportImagePixelArea; using MagickLib::ExtentImage; using MagickLib::FileOpenError; using MagickLib::FileOpenFatalError; using MagickLib::FileOpenWarning; using MagickLib::FlattenImages; using MagickLib::FlipImage; using MagickLib::FlopImage; using MagickLib::FormatString; using MagickLib::FrameImage; using MagickLib::FrameInfo; using MagickLib::GammaImage; using MagickLib::GammaImage; using MagickLib::GaussianBlurImage; using MagickLib::GaussianBlurImageChannel; using MagickLib::GetBlobSize; using MagickLib::GetCacheViewIndexes; using MagickLib::GetCacheViewPixels; using MagickLib::GetColorTuple; using MagickLib::GetDrawInfo; using MagickLib::GetExceptionInfo; using MagickLib::GetGeometry; using MagickLib::GetImageAttribute; using MagickLib::GetImageBoundingBox; using MagickLib::GetImageChannelDepth; using MagickLib::GetImageClipMask; using MagickLib::GetImageDepth; using MagickLib::GetImageGeometry; using MagickLib::GetImageInfo; using MagickLib::GetImagePixels; using MagickLib::GetImageProfile; using MagickLib::GetImageQuantizeError; using MagickLib::GetImageStatistics; using MagickLib::GetImageType; using MagickLib::GetMagickGeometry; using MagickLib::GetMagickInfo; using MagickLib::GetMagickInfoArray; using MagickLib::GetMagickRegistry; using MagickLib::GetNumberColors; using MagickLib::GetPageGeometry; using MagickLib::GetQuantizeInfo; using MagickLib::GetTypeMetrics; using MagickLib::GlobExpression; using MagickLib::GreaterValue; using MagickLib::HaldClutImage; using MagickLib::HSLTransform; using MagickLib::HeightValue; using MagickLib::IdentityAffine; using MagickLib::ImageAttribute; using MagickLib::ImageError; using MagickLib::ImageFatalError; using MagickLib::ImageInfo; using MagickLib::ImageInfoRegistryType; using MagickLib::ImageRegistryType; using MagickLib::ImageToBlob; using MagickLib::ImageWarning; using MagickLib::ImplodeImage; using MagickLib::ImportImagePixelArea; using MagickLib::IsEventLogging; using MagickLib::IsGeometry; using MagickLib::IsImagesEqual; using MagickLib::IsSubimage; using MagickLib::LessValue; using MagickLib::LevelImage; using MagickLib::LevelImageChannel; using MagickLib::LocaleCompare; using MagickLib::LogMagickEvent; using MagickLib::MagickFree; using MagickLib::MagickInfo; using MagickLib::MagickMalloc; using MagickLib::MagickRealloc; using MagickLib::MagickStrlCpy; using MagickLib::MagickToMime; using MagickLib::MagnifyImage; using MagickLib::MapImage; using MagickLib::MatteFloodfillImage; using MagickLib::MedianFilterImage; using MagickLib::MinifyImage; using MagickLib::MinimumValue; using MagickLib::MissingDelegateError; using MagickLib::MissingDelegateFatalError; using MagickLib::MissingDelegateWarning; using MagickLib::ModulateImage; using MagickLib::ModuleError; using MagickLib::ModuleFatalError; using MagickLib::ModuleWarning; using MagickLib::MonitorError; using MagickLib::MonitorFatalError; using MagickLib::MonitorWarning; using MagickLib::MontageInfo; using MagickLib::MotionBlurImage; using MagickLib::NegateImage; using MagickLib::NoValue; using MagickLib::NoiseType; using MagickLib::NormalizeImage; using MagickLib::OilPaintImage; using MagickLib::OpaqueImage; using MagickLib::OpenCacheView; using MagickLib::OptionError; using MagickLib::OptionFatalError; using MagickLib::OptionWarning; using MagickLib::PercentValue; using MagickLib::PingBlob; using MagickLib::PingImage; using MagickLib::PointInfo; using MagickLib::PopImagePixels; using MagickLib::ProfileImage; using MagickLib::ProfileInfo; using MagickLib::PushImagePixels; using MagickLib::QuantizeImage; using MagickLib::QuantizeInfo; using MagickLib::QuantumOperatorImage; using MagickLib::QuantumOperatorRegionImage; using MagickLib::QueryColorDatabase; using MagickLib::RGBTransformImage; using MagickLib::RaiseImage; using MagickLib::RandomChannelThresholdImage; using MagickLib::ReadImage; using MagickLib::RectangleInfo; using MagickLib::RectangleInfo; using MagickLib::ReduceNoiseImage; using MagickLib::RegisterMagickInfo; using MagickLib::RegistryError; using MagickLib::RegistryFatalError; using MagickLib::RegistryType; using MagickLib::RegistryWarning; using MagickLib::RemoveDefinitions; using MagickLib::ResizeImage; using MagickLib::ResourceLimitError; using MagickLib::ResourceLimitFatalError; using MagickLib::ResourceLimitWarning; using MagickLib::RollImage; using MagickLib::RotateImage; using MagickLib::SampleImage; using MagickLib::ScaleImage; using MagickLib::SegmentImage; using MagickLib::SetCacheViewPixels; using MagickLib::SetClientName; using MagickLib::SetImage; using MagickLib::SetImageAttribute; using MagickLib::SetImageChannelDepth; using MagickLib::SetImageClipMask; using MagickLib::SetImageDepth; using MagickLib::SetImageInfo; using MagickLib::SetImageOpacity; using MagickLib::SetImagePixels; using MagickLib::SetImageProfile; using MagickLib::SetImageType; using MagickLib::SetLogEventMask; using MagickLib::SetMagickInfo; using MagickLib::SetMagickRegistry; using MagickLib::SetMagickResourceLimit; using MagickLib::SetMagickResourceLimit; using MagickLib::ShadeImage; using MagickLib::SharpenImage; using MagickLib::SharpenImageChannel; using MagickLib::ShaveImage; using MagickLib::ShearImage; using MagickLib::SignatureImage; using MagickLib::SolarizeImage; using MagickLib::SpreadImage; using MagickLib::SteganoImage; using MagickLib::StereoImage; using MagickLib::StreamError; using MagickLib::StreamFatalError; using MagickLib::StreamWarning; using MagickLib::SwirlImage; using MagickLib::SyncCacheViewPixels; using MagickLib::SyncImage; using MagickLib::SyncImagePixels; using MagickLib::TextureImage; using MagickLib::ThresholdImage; using MagickLib::ThrowException; using MagickLib::ThrowLoggedException; using MagickLib::ThumbnailImage; using MagickLib::TransformHSL; using MagickLib::TransformImage; using MagickLib::TransformRGBImage; using MagickLib::TransparentImage; using MagickLib::TypeError; using MagickLib::TypeFatalError; using MagickLib::TypeWarning; using MagickLib::UndefinedException; using MagickLib::UndefinedRegistryType; using MagickLib::UnregisterMagickInfo; using MagickLib::UnsharpMaskImage; using MagickLib::UnsharpMaskImageChannel; using MagickLib::ViewInfo; using MagickLib::WaveImage; using MagickLib::WidthValue; using MagickLib::WriteImage; using MagickLib::XNegative; using MagickLib::XServerError; using MagickLib::XServerFatalError; using MagickLib::XServerWarning; using MagickLib::XValue; using MagickLib::YNegative; using MagickLib::YValue; using MagickLib::ZoomImage; #endif // MAGICK_IMPLEMENTATION } #endif // Magick_Include_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Montage.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // // Definition of Montage class used to specify montage options. // #if !defined(Magick_Montage_header) #define Magick_Montage_header #include "Magick++/Include.h" #include #include "Magick++/Color.h" #include "Magick++/Geometry.h" // // Basic (Un-framed) Montage // namespace Magick { class MagickDLLDecl Montage { public: Montage( void ); virtual ~Montage( void ); // Specifies the background color that thumbnails are imaged upon. void backgroundColor ( const Color &backgroundColor_ ); Color backgroundColor ( void ) const; // Specifies the image composition algorithm for thumbnails. This // controls the algorithm by which the thumbnail image is placed // on the background. Use of OverCompositeOp is recommended for // use with images that have transparency. This option may have // negative side-effects for images without transparency. void compose ( CompositeOperator compose_ ); CompositeOperator compose ( void ) const; // Specifies the image filename to be used for the generated // montage images. To handle the case were multiple montage images // are generated, a printf-style format may be embedded within the // filename. For example, a filename specification of // image%02d.miff names the montage images as image00.miff, // image01.miff, etc. void fileName( const std::string &fileName_ ); std::string fileName( void ) const; // Specifies the fill color to use for the label text. void fillColor ( const Color &fill_ ); Color fillColor ( void ) const; // Specifies the thumbnail label font. void font ( const std::string &font_ ); std::string font ( void ) const; // Specifies the size of the generated thumbnail. void geometry ( const Geometry &geometry_ ); Geometry geometry ( void ) const; // Specifies the thumbnail positioning within the specified // geometry area. If the thumbnail is smaller in any dimension // than the geometry, then it is placed according to this // specification void gravity ( GravityType gravity_ ); GravityType gravity ( void ) const; // Specifies the format used for the image label. Special format // characters may be embedded in the format string to include // information about the image. void label( const std::string &label_ ); std::string label( void ) const; // Specifies the pen color to use for the label text (same as fill). void penColor ( const Color &pen_ ); Color penColor ( void ) const; // Specifies the thumbnail label font size. void pointSize ( unsigned int pointSize_ ); unsigned int pointSize ( void ) const; // Enable/disable drop-shadow on thumbnails. void shadow ( bool shadow_ ); bool shadow ( void ) const; // Specifies the stroke color to use for the label text . void strokeColor ( const Color &stroke_ ); Color strokeColor ( void ) const; // Specifies a texture image to use as montage background. The // built-in textures "granite:" and "plasma:" are available. A // texture is the same as a background image. void texture ( const std::string &texture_ ); std::string texture ( void ) const; // Specifies the maximum number of montage columns and rows in the // montage. The montage is built by filling out all cells in a row // before advancing to the next row. Once the montage has reached // the maximum number of columns and rows, a new montage image is // started. void tile ( const Geometry &tile_ ); Geometry tile ( void ) const; // Specifies the montage title void title ( const std::string &title_ ); std::string title ( void ) const; // Specifies a montage color to set transparent. This option can // be set the same as the background color in order for the // thumbnails to appear without a background when rendered on an // HTML page. For best effect, ensure that the transparent color // selected does not occur in the rendered thumbnail colors. void transparentColor ( const Color &transparentColor_ ); Color transparentColor ( void ) const; // // Implementation methods/members // // Update elements in existing MontageInfo structure virtual void updateMontageInfo ( MagickLib::MontageInfo &montageInfo_ ) const; protected: private: Color _backgroundColor; // Color that thumbnails are composed on CompositeOperator _compose; // Composition algorithm to use (e.g. ReplaceCompositeOp) std::string _fileName; // Filename to save montages to Color _fill; // Fill color std::string _font; // Label font Geometry _geometry; // Thumbnail width & height plus border width & height GravityType _gravity; // Thumbnail position (e.g. SouthWestGravity) std::string _label; // Thumbnail label (applied to image prior to montage) unsigned int _pointSize; // Font point size bool _shadow; // Enable drop-shadows on thumbnails Color _stroke; // Outline color std::string _texture; // Background texture image Geometry _tile; // Thumbnail rows and colmns std::string _title; // Montage title Color _transparentColor; // Transparent color }; // // Montage With Frames (Extends Basic Montage) // class MagickDLLDecl MontageFramed : public Montage { public: MontageFramed ( void ); /* virtual */ ~MontageFramed ( void ); // Specifies the background color within the thumbnail frame. void borderColor ( const Color &borderColor_ ); Color borderColor ( void ) const; // Specifies the border (in pixels) to place between a thumbnail // and its surrounding frame. This option only takes effect if // thumbnail frames are enabled (via frameGeometry) and the // thumbnail geometry specification doesn't also specify the // thumbnail border width. void borderWidth ( unsigned int borderWidth_ ); unsigned int borderWidth ( void ) const; // Specifies the geometry specification for frame to place around // thumbnail. If this parameter is not specified, then the montage // is unframed. void frameGeometry ( const Geometry &frame_ ); Geometry frameGeometry ( void ) const; // Specifies the thumbnail frame color. void matteColor ( const Color &matteColor_ ); Color matteColor ( void ) const; // // Implementation methods/members // // Update elements in existing MontageInfo structure /* virtual */ void updateMontageInfo ( MagickLib::MontageInfo &montageInfo_ ) const; protected: private: Color _borderColor; // Frame border color unsigned int _borderWidth; // Pixels between thumbnail and surrounding frame Geometry _frame; // Frame geometry (width & height frame thickness) Color _matteColor; // Frame foreground color }; } // namespace Magick // // Inlines // // // Implementation of Montage // inline void Magick::Montage::backgroundColor ( const Magick::Color &backgroundColor_ ) { _backgroundColor = backgroundColor_; } inline Magick::Color Magick::Montage::backgroundColor ( void ) const { return _backgroundColor; } inline void Magick::Montage::compose ( Magick::CompositeOperator compose_ ) { _compose = compose_; } inline Magick::CompositeOperator Magick::Montage::compose ( void ) const { return _compose; } inline void Magick::Montage::fileName( const std::string &fileName_ ) { _fileName = fileName_; } inline std::string Magick::Montage::fileName( void ) const { return _fileName; } inline void Magick::Montage::fillColor ( const Color &fill_ ) { _fill=fill_; } inline Magick::Color Magick::Montage::fillColor ( void ) const { return _fill; } inline void Magick::Montage::font ( const std::string &font_ ) { _font = font_; } inline std::string Magick::Montage::font ( void ) const { return _font; } inline void Magick::Montage::geometry ( const Magick::Geometry &geometry_ ) { _geometry = geometry_; } inline Magick::Geometry Magick::Montage::geometry ( void ) const { return _geometry; } inline void Magick::Montage::gravity ( Magick::GravityType gravity_ ) { _gravity = gravity_; } inline Magick::GravityType Magick::Montage::gravity ( void ) const { return _gravity; } // Apply as attribute to all images before doing montage inline void Magick::Montage::label( const std::string &label_ ) { _label = label_; } inline std::string Magick::Montage::label( void ) const { return _label; } inline void Magick::Montage::penColor ( const Color &pen_ ) { _fill=pen_; _stroke=Color("none"); } inline Magick::Color Magick::Montage::penColor ( void ) const { return _fill; } inline void Magick::Montage::pointSize ( unsigned int pointSize_ ) { _pointSize = pointSize_; } inline unsigned int Magick::Montage::pointSize ( void ) const { return _pointSize; } inline void Magick::Montage::shadow ( bool shadow_ ) { _shadow = shadow_; } inline bool Magick::Montage::shadow ( void ) const { return _shadow; } inline void Magick::Montage::strokeColor ( const Color &stroke_ ) { _stroke=stroke_; } inline Magick::Color Magick::Montage::strokeColor ( void ) const { return _stroke; } inline void Magick::Montage::texture ( const std::string &texture_ ) { _texture = texture_; } inline std::string Magick::Montage::texture ( void ) const { return _texture; } inline void Magick::Montage::tile ( const Geometry &tile_ ) { _tile = tile_; } inline Magick::Geometry Magick::Montage::tile ( void ) const { return _tile; } inline void Magick::Montage::title ( const std::string &title_ ) { _title = title_; } inline std::string Magick::Montage::title ( void ) const { return _title; } // Applied after the fact to montage with TransparentImage() inline void Magick::Montage::transparentColor ( const Magick::Color &transparentColor_ ) { _transparentColor = transparentColor_; } inline Magick::Color Magick::Montage::transparentColor ( void ) const { return _transparentColor; } // // Implementation of MontageFramed // inline void Magick::MontageFramed::borderColor ( const Magick::Color &borderColor_ ) { _borderColor = borderColor_; } inline Magick::Color Magick::MontageFramed::borderColor ( void ) const { return _borderColor; } inline void Magick::MontageFramed::borderWidth ( unsigned int borderWidth_ ) { _borderWidth = borderWidth_; } inline unsigned int Magick::MontageFramed::borderWidth ( void ) const { return _borderWidth; } inline void Magick::MontageFramed::frameGeometry ( const Magick::Geometry &frame_ ) { _frame = frame_; } inline Magick::Geometry Magick::MontageFramed::frameGeometry ( void ) const { return _frame; } inline void Magick::MontageFramed::matteColor ( const Magick::Color &matteColor_ ) { _matteColor = matteColor_; } inline Magick::Color Magick::MontageFramed::matteColor ( void ) const { return _matteColor; } #endif // Magick_Montage_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/Pixels.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002 // // Representation of a pixel view. // #if !defined(Magick_Pixels_header) #define Magick_Pixels_header #include "Magick++/Include.h" #include "Magick++/Color.h" #include "Magick++/Image.h" namespace Magick { class MagickDLLDecl Pixels { public: // Construct pixel view using specified image. Pixels( Magick::Image &image_ ); // Destroy pixel view ~Pixels( void ); // Transfer pixels from the image to the pixel view as defined by // the specified region. Modified pixels may be subsequently // transferred back to the image via sync. PixelPacket* get ( const int x_, const int y_, const unsigned int columns_,const unsigned int rows_ ); // Transfer read-only pixels from the image to the pixel view as // defined by the specified region. const PixelPacket* getConst ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ); // Transfers the image view pixels to the image. void sync ( void ); // Allocate a pixel view region to store image pixels as defined // by the region rectangle. This area is subsequently transferred // from the pixel view to the image via sync. PixelPacket* set ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ); // Return pixel colormap index array IndexPacket* indexes ( void ); // Left ordinate of view int x ( void ) const; // Top ordinate of view int y ( void ) const; // Width of view unsigned int columns ( void ) const; // Height of view unsigned int rows ( void ) const; #if 0 // Transfer one or more pixel components from a buffer or file // into the image pixel view of an image. Used to support image // decoders. void decode ( const QuantumType quantum_, const unsigned char *source_ ) { MagickLib::ReadPixelCache( _image.image(), quantum_, source_ ); } // Transfer one or more pixel components from the image pixel // view to a buffer or file. Used to support image encoders. void encode ( const QuantumType quantum_, const unsigned char *destination_ ) { MagickLib::WritePixelCache( _image.image(), quantum_, destination_ ); } #endif private: // Copying and assigning Pixels is not supported. Pixels( const Pixels& pixels_ ); const Pixels& operator=( const Pixels& pixels_ ); Magick::Image _image; // Image reference MagickLib::ViewInfo* _view; // Image view handle int _x; // Left ordinate of view int _y; // Top ordinate of view unsigned int _columns; // Width of view unsigned int _rows; // Height of view MagickLib:: ExceptionInfo _exception; // Any thrown exception }; // class Pixels } // Magick namespace // // Inline methods // // Left ordinate of view inline int Magick::Pixels::x ( void ) const { return _x; } // Top ordinate of view inline int Magick::Pixels::y ( void ) const { return _y; } // Width of view inline unsigned int Magick::Pixels::columns ( void ) const { return _columns; } // Height of view inline unsigned int Magick::Pixels::rows ( void ) const { return _rows; } #endif // Magick_Pixels_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/STL.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2018 // // Definition and implementation of template functions for using // Magick::Image with STL containers. // #ifndef Magick_STL_header #define Magick_STL_header #include "Magick++/Include.h" #include #include #include #include #include #include "Magick++/CoderInfo.h" #include "Magick++/Drawable.h" #include "Magick++/Exception.h" #include "Magick++/Montage.h" namespace Magick { // // STL function object declarations/definitions // // Function objects provide the means to invoke an operation on one // or more image objects in an STL-compatable container. The // arguments to the function object constructor(s) are compatible // with the arguments to the equivalent Image class method and // provide the means to supply these options when the function // object is invoked. // For example, to read a GIF animation, set the color red to // transparent for all frames, and write back out: // // list images; // readImages( &images, "animation.gif" ); // for_each( images.begin(), images.end(), transparentImage( "red" ) ); // writeImages( images.begin(), images.end(), "animation.gif" ); // Local adaptive threshold image // http://www.dai.ed.ac.uk/HIPR2/adpthrsh.htm // Width x height define the size of the pixel neighborhood // offset = constant to subtract from pixel neighborhood mean class MagickDLLDecl adaptiveThresholdImage : public std::unary_function { public: adaptiveThresholdImage( const unsigned int width_, const unsigned int height_, const double offset_ = 0.0 ); void operator()( Image &image_ ) const; private: unsigned int _width; unsigned int _height; double _offset; }; // Add noise to image with specified noise type class MagickDLLDecl addNoiseImage : public std::unary_function { public: addNoiseImage ( NoiseType noiseType_ ); void operator()( Image &image_ ) const; private: NoiseType _noiseType; }; // Transform image by specified affine (or free transform) matrix. class MagickDLLDecl affineTransformImage : public std::unary_function { public: affineTransformImage( const DrawableAffine &affine_ ); void operator()( Image &image_ ) const; private: DrawableAffine _affine; }; // Annotate image (draw text on image) class MagickDLLDecl annotateImage : public std::unary_function { public: // Annotate using specified text, and placement location annotateImage ( const std::string &text_, const Geometry &geometry_ ); // Annotate using specified text, bounding area, and placement // gravity annotateImage ( const std::string &text_, const Geometry &geometry_, const GravityType gravity_ ); // Annotate with text using specified text, bounding area, // placement gravity, and rotation. annotateImage ( const std::string &text_, const Geometry &geometry_, const GravityType gravity_, const double degrees_ ); // Annotate with text (bounding area is entire image) and // placement gravity. annotateImage ( const std::string &text_, const GravityType gravity_ ); void operator()( Image &image_ ) const; private: // Copy constructor and assignment are not supported annotateImage(const annotateImage&); annotateImage& operator=(const annotateImage&); const std::string _text; const Geometry _geometry; const GravityType _gravity; const double _degrees; }; // Blur image with specified blur factor class MagickDLLDecl blurImage : public std::unary_function { public: blurImage( const double radius_ = 1, const double sigma_ = 0.5 ); void operator()( Image &image_ ) const; private: double _radius; double _sigma; }; // Border image (add border to image) class MagickDLLDecl borderImage : public std::unary_function { public: borderImage( const Geometry &geometry_ = borderGeometryDefault ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Extract channel from image class MagickDLLDecl channelImage : public std::unary_function { public: channelImage( const ChannelType channel_ ); void operator()( Image &image_ ) const; private: ChannelType _channel; }; // Charcoal effect image (looks like charcoal sketch) class MagickDLLDecl charcoalImage : public std::unary_function { public: charcoalImage( const double radius_ = 1, const double sigma_ = 0.5 ); void operator()( Image &image_ ) const; private: double _radius; double _sigma; }; // Chop image (remove vertical or horizontal subregion of image) class MagickDLLDecl chopImage : public std::unary_function { public: chopImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Colorize image using pen color at specified percent opacity class MagickDLLDecl colorizeImage : public std::unary_function { public: colorizeImage( const unsigned int opacityRed_, const unsigned int opacityGreen_, const unsigned int opacityBlue_, const Color &penColor_ ); colorizeImage( const unsigned int opacity_, const Color &penColor_ ); void operator()( Image &image_ ) const; private: unsigned int _opacityRed; unsigned int _opacityGreen; unsigned int _opacityBlue; Color _penColor; }; // Bake in the ASC-CDL, which is a convention for the for the // exchange of basic primary color grading information between for // the exchange of basic primary color grading information between // equipment and software from different manufacturers. It is a // useful transform for other purposes as well. class MagickDLLDecl cdlImage : public std::unary_function { public: cdlImage( const std::string &cdl_ ); void operator()( Image &image_ ) const; private: std::string _cdl; }; // Apply a color matrix to the image channels. The user supplied // matrix may be of order 1 to 5 (1x1 through 5x5). class MagickDLLDecl colorMatrixImage : public std::unary_function { public: colorMatrixImage( const unsigned int order_, const double *color_matrix_ ); void operator()( Image &image_ ) const; private: unsigned int _order; const double *_color_matrix; }; // Convert the image colorspace representation class MagickDLLDecl colorSpaceImage : public std::unary_function { public: colorSpaceImage( ColorspaceType colorSpace_ ); void operator()( Image &image_ ) const; private: ColorspaceType _colorSpace; }; // Comment image (add comment string to image) class MagickDLLDecl commentImage : public std::unary_function { public: commentImage( const std::string &comment_ ); void operator()( Image &image_ ) const; private: std::string _comment; }; // Compose an image onto another at specified offset and using // specified algorithm class MagickDLLDecl compositeImage : public std::unary_function { public: compositeImage( const Image &compositeImage_, int xOffset_, int yOffset_, CompositeOperator compose_ = InCompositeOp ); compositeImage( const Image &compositeImage_, const Geometry &offset_, CompositeOperator compose_ = InCompositeOp ); void operator()( Image &image_ ) const; private: Image _compositeImage; int _xOffset; int _yOffset; CompositeOperator _compose; }; // Contrast image (enhance intensity differences in image) class MagickDLLDecl contrastImage : public std::unary_function { public: contrastImage( const unsigned int sharpen_ ); void operator()( Image &image_ ) const; private: unsigned int _sharpen; }; // Crop image (subregion of original image) class MagickDLLDecl cropImage : public std::unary_function { public: cropImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Cycle image colormap class MagickDLLDecl cycleColormapImage : public std::unary_function { public: cycleColormapImage( const int amount_ ); void operator()( Image &image_ ) const; private: int _amount; }; // Despeckle image (reduce speckle noise) class MagickDLLDecl despeckleImage : public std::unary_function { public: despeckleImage( void ); void operator()( Image &image_ ) const; private: }; // Draw on image class MagickDLLDecl drawImage : public std::unary_function { public: // Draw on image using a single drawable // Store in list to make implementation easier drawImage( const Drawable &drawable_ ); // Draw on image using a drawable list drawImage( const DrawableList &drawable_ ); void operator()( Image &image_ ) const; private: DrawableList _drawableList; }; // Edge image (hilight edges in image) class MagickDLLDecl edgeImage : public std::unary_function { public: edgeImage( const double radius_ = 0.0 ); void operator()( Image &image_ ) const; private: double _radius; }; // Emboss image (hilight edges with 3D effect) class MagickDLLDecl embossImage : public std::unary_function { public: embossImage( void ); embossImage( const double radius_, const double sigma_ ); void operator()( Image &image_ ) const; private: double _radius; double _sigma; }; // Enhance image (minimize noise) class MagickDLLDecl enhanceImage : public std::unary_function { public: enhanceImage( void ); void operator()( Image &image_ ) const; private: }; // Equalize image (histogram equalization) class MagickDLLDecl equalizeImage : public std::unary_function { public: equalizeImage( void ); void operator()( Image &image_ ) const; private: }; // Create an image canvas using background color sized according to // geometry and composite existing image on it, with image placement // controlled by gravity. Parameters are obtained from existing // image properties if they are not specified via a method // parameter. Parameters which are supported by image properties // (gravity and backgroundColor) update those image properties as a // side-effect. class MagickDLLDecl extentImage : public std::unary_function { public: // Extent image using a geometry extentImage ( const Geometry &geometry_ ); // Extent image using a geometry & gravity extentImage ( const Geometry &geometry_, const GravityType &gravity_ ); // Extent image using a geometry & background color extentImage ( const Geometry &geometry_, const Color &backgroundColor_ ); // Extent image using a geometry, background color & gravity extentImage ( const Geometry &geometry_, const Color &backgroundColor_, const GravityType &gravity_ ); void operator()( Image &image_ ) const; private: // Copy constructor and assignment are not supported extentImage(const extentImage&); extentImage& operator=(const extentImage&); const Geometry _geometry; const Color _backgroundColor; const GravityType _gravity; }; // Color to use when filling drawn objects class MagickDLLDecl fillColorImage : public std::unary_function { public: fillColorImage( const Color &fillColor_ ); void operator()( Image &image_ ) const; private: Color _fillColor; }; // Flip image (reflect each scanline in the vertical direction) class MagickDLLDecl flipImage : public std::unary_function { public: flipImage( void ); void operator()( Image &image_ ) const; private: }; // Flood-fill image with color class MagickDLLDecl floodFillColorImage : public std::unary_function { public: // Flood-fill color across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. floodFillColorImage( const unsigned int x_, const unsigned int y_, const Color &fillColor_ ); floodFillColorImage( const Geometry &point_, const Color &fillColor_ ); // Flood-fill color across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. floodFillColorImage( const unsigned int x_, const unsigned int y_, const Color &fillColor_, const Color &borderColor_ ); floodFillColorImage( const Geometry &point_, const Color &fillColor_, const Color &borderColor_ ); void operator()( Image &image_ ) const; private: unsigned int _x; unsigned int _y; Color _fillColor; Color _borderColor; }; // Flood-fill image with texture class MagickDLLDecl floodFillTextureImage : public std::unary_function { public: // Flood-fill texture across pixels that match the color of the // target pixel and are neighbors of the target pixel. // Uses current fuzz setting when determining color match. floodFillTextureImage( const unsigned int x_, const unsigned int y_, const Image &texture_ ); floodFillTextureImage( const Geometry &point_, const Image &texture_ ); // Flood-fill texture across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. floodFillTextureImage( const unsigned int x_, const unsigned int y_, const Image &texture_, const Color &borderColor_ ); floodFillTextureImage( const Geometry &point_, const Image &texture_, const Color &borderColor_ ); void operator()( Image &image_ ) const; private: unsigned int _x; unsigned int _y; Image _texture; Color _borderColor; }; // Flop image (reflect each scanline in the horizontal direction) class MagickDLLDecl flopImage : public std::unary_function { public: flopImage( void ); void operator()( Image &image_ ) const; private: }; // Frame image class MagickDLLDecl frameImage : public std::unary_function { public: frameImage( const Geometry &geometry_ = frameGeometryDefault ); frameImage( const unsigned int width_, const unsigned int height_, const int innerBevel_ = 6, const int outerBevel_ = 6 ); void operator()( Image &image_ ) const; private: unsigned int _width; unsigned int _height; int _outerBevel; int _innerBevel; }; // Gamma correct image class MagickDLLDecl gammaImage : public std::unary_function { public: gammaImage( const double gamma_ ); gammaImage ( const double gammaRed_, const double gammaGreen_, const double gammaBlue_ ); void operator()( Image &image_ ) const; private: double _gammaRed; double _gammaGreen; double _gammaBlue; }; // Gaussian blur image // The number of neighbor pixels to be included in the convolution // mask is specified by 'width_'. The standard deviation of the // gaussian bell curve is specified by 'sigma_'. class MagickDLLDecl gaussianBlurImage : public std::unary_function { public: gaussianBlurImage( const double width_, const double sigma_ ); void operator()( Image &image_ ) const; private: double _width; double _sigma; }; // Implode image (special effect) class MagickDLLDecl implodeImage : public std::unary_function { public: implodeImage( const double factor_ = 50 ); void operator()( Image &image_ ) const; private: double _factor; }; // Apply a color lookup table (Hald CLUT) to the image. class MagickDLLDecl haldClutImage : public std::unary_function { public: haldClutImage( const Image &haldClutImage_ ); void operator()( Image &image_ ) const; private: Image _haldClutImage; }; // Set image validity. Valid images become empty (inValid) if // argument is false. class MagickDLLDecl isValidImage : public std::unary_function { public: isValidImage( const bool isValid_ ); void operator()( Image &image_ ) const; private: bool _isValid; }; // Label image class MagickDLLDecl labelImage : public std::unary_function { public: labelImage( const std::string &label_ ); void operator()( Image &image_ ) const; private: std::string _label; }; // Level image class MagickDLLDecl levelImage : public std::unary_function { public: levelImage( const double black_point, const double white_point, const double mid_point=1.0 ); void operator()( Image &image_ ) const; private: double _black_point; double _white_point; double _mid_point; }; // Level image channel class MagickDLLDecl levelChannelImage : public std::unary_function { public: levelChannelImage( const Magick::ChannelType channel, const double black_point, const double white_point, const double mid_point=1.0 ); void operator()( Image &image_ ) const; private: Magick::ChannelType _channel; double _black_point; double _white_point; double _mid_point; }; // Magnify image by integral size class MagickDLLDecl magnifyImage : public std::unary_function { public: magnifyImage( void ); void operator()( Image &image_ ) const; private: }; // Remap image colors with closest color from reference image class MagickDLLDecl mapImage : public std::unary_function { public: mapImage( const Image &mapImage_ , const bool dither_ = false ); void operator()( Image &image_ ) const; private: Image _mapImage; bool _dither; }; // Floodfill designated area with a matte value class MagickDLLDecl matteFloodfillImage : public std::unary_function { public: matteFloodfillImage( const Color &target_ , const unsigned int matte_, const int x_, const int y_, const PaintMethod method_ ); void operator()( Image &image_ ) const; private: Color _target; unsigned int _matte; int _x; int _y; PaintMethod _method; }; // Filter image by replacing each pixel component with the median // color in a circular neighborhood class MagickDLLDecl medianFilterImage : public std::unary_function { public: medianFilterImage( const double radius_ = 0.0 ); void operator()( Image &image_ ) const; private: double _radius; }; // Reduce image by integral size class MagickDLLDecl minifyImage : public std::unary_function { public: minifyImage( void ); void operator()( Image &image_ ) const; private: }; // Modulate percent hue, saturation, and brightness of an image. // Modulation of saturation and brightness is as a ratio of the // current value (1.0 for no change). Modulation of hue is an // absolute rotation of -180 degrees to +180 degrees from the // current position corresponding to an argument range of 0 to 2.0 // (1.0 for no change). class MagickDLLDecl modulateImage : public std::unary_function { public: modulateImage( const double brightness_, const double saturation_, const double hue_ ); void operator()( Image &image_ ) const; private: double _brightness; double _saturation; double _hue; }; // Negate colors in image. Set grayscale to only negate grayscale // values in image. class MagickDLLDecl negateImage : public std::unary_function { public: negateImage( const bool grayscale_ = false ); void operator()( Image &image_ ) const; private: bool _grayscale; }; // Normalize image (increase contrast by normalizing the pixel // values to span the full range of color values) class MagickDLLDecl normalizeImage : public std::unary_function { public: normalizeImage( void ); void operator()( Image &image_ ) const; private: }; // Oilpaint image (image looks like oil painting) class MagickDLLDecl oilPaintImage : public std::unary_function { public: oilPaintImage( const double radius_ = 3 ); void operator()( Image &image_ ) const; private: double _radius; }; // Set or attenuate the image opacity channel. If the image pixels // are opaque then they are set to the specified opacity value, // otherwise they are blended with the supplied opacity value. The // value of opacity_ ranges from 0 (completely opaque) to // MaxRGB. The defines OpaqueOpacity and TransparentOpacity are // available to specify completely opaque or completely transparent, // respectively. class MagickDLLDecl opacityImage : public std::unary_function { public: opacityImage( const unsigned int opacity_ ); void operator()( Image &image_ ) const; private: unsigned int _opacity; }; // Change color of opaque pixel to specified pen color. class MagickDLLDecl opaqueImage : public std::unary_function { public: opaqueImage( const Color &opaqueColor_, const Color &penColor_ ); void operator()( Image &image_ ) const; private: Color _opaqueColor; Color _penColor; }; // Quantize image (reduce number of colors) class MagickDLLDecl quantizeImage : public std::unary_function { public: quantizeImage( const bool measureError_ = false ); void operator()( Image &image_ ) const; private: bool _measureError; }; // Raise image (lighten or darken the edges of an image to give a // 3-D raised or lowered effect) class MagickDLLDecl raiseImage : public std::unary_function { public: raiseImage( const Geometry &geometry_ = raiseGeometryDefault, const bool raisedFlag_ = false ); void operator()( Image &image_ ) const; private: Geometry _geometry; bool _raisedFlag; }; // Reduce noise in image using a noise peak elimination filter class MagickDLLDecl reduceNoiseImage : public std::unary_function { public: reduceNoiseImage( void ); reduceNoiseImage (const unsigned int order_ ); void operator()( Image &image_ ) const; private: unsigned int _order; }; // Resize image to a certain geomtry class MagickDLLDecl resizeImage : public std::unary_function { public: resizeImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Roll image (rolls image vertically and horizontally) by specified // number of columnms and rows) class MagickDLLDecl rollImage : public std::unary_function { public: rollImage( const Geometry &roll_ ); rollImage( const int columns_, const int rows_ ); void operator()( Image &image_ ) const; private: int _columns; int _rows; }; // Rotate image counter-clockwise by specified number of degrees. class MagickDLLDecl rotateImage : public std::unary_function { public: rotateImage( const double degrees_ ); void operator()( Image &image_ ) const; private: double _degrees; }; // Resize image by using pixel sampling algorithm class MagickDLLDecl sampleImage : public std::unary_function { public: sampleImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Resize image by using simple ratio algorithm class MagickDLLDecl scaleImage : public std::unary_function { public: scaleImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Segment (coalesce similar image components) by analyzing the // histograms of the color components and identifying units that are // homogeneous with the fuzzy c-means technique. // Also uses QuantizeColorSpace and Verbose image attributes class MagickDLLDecl segmentImage : public std::unary_function { public: segmentImage( const double clusterThreshold_ = 1.0, const double smoothingThreshold_ = 1.5 ); void operator()( Image &image_ ) const; private: double _clusterThreshold; double _smoothingThreshold; }; // Shade image using distant light source class MagickDLLDecl shadeImage : public std::unary_function { public: shadeImage( const double azimuth_ = 30, const double elevation_ = 30, const bool colorShading_ = false ); void operator()( Image &image_ ) const; private: double _azimuth; double _elevation; bool _colorShading; }; // Sharpen pixels in image class MagickDLLDecl sharpenImage : public std::unary_function { public: sharpenImage( const double radius_ = 1, const double sigma_ = 0.5 ); void operator()( Image &image_ ) const; private: double _radius; double _sigma; }; // Shave pixels from image edges. class MagickDLLDecl shaveImage : public std::unary_function { public: shaveImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Shear image (create parallelogram by sliding image by X or Y axis) class MagickDLLDecl shearImage : public std::unary_function { public: shearImage( const double xShearAngle_, const double yShearAngle_ ); void operator()( Image &image_ ) const; private: double _xShearAngle; double _yShearAngle; }; // Solarize image (similar to effect seen when exposing a // photographic film to light during the development process) class MagickDLLDecl solarizeImage : public std::unary_function { public: solarizeImage( const double factor_ ); void operator()( Image &image_ ) const; private: double _factor; }; // Spread pixels randomly within image by specified ammount class MagickDLLDecl spreadImage : public std::unary_function { public: spreadImage( const unsigned int amount_ = 3 ); void operator()( Image &image_ ) const; private: unsigned int _amount; }; // Add a digital watermark to the image (based on second image) class MagickDLLDecl steganoImage : public std::unary_function { public: steganoImage( const Image &waterMark_ ); void operator()( Image &image_ ) const; private: Image _waterMark; }; // Create an image which appears in stereo when viewed with red-blue glasses // (Red image on left, blue on right) class MagickDLLDecl stereoImage : public std::unary_function { public: stereoImage( const Image &rightImage_ ); void operator()( Image &image_ ) const; private: Image _rightImage; }; // Color to use when drawing object outlines class MagickDLLDecl strokeColorImage : public std::unary_function { public: strokeColorImage( const Color &strokeColor_ ); void operator()( Image &image_ ) const; private: Color _strokeColor; }; // Swirl image (image pixels are rotated by degrees) class MagickDLLDecl swirlImage : public std::unary_function { public: swirlImage( const double degrees_ ); void operator()( Image &image_ ) const; private: double _degrees; }; // Remove all profiles and text attributes from the image. class MagickDLLDecl stripImage : public std::unary_function { public: stripImage( void ); void operator()( Image &image_ ) const; private: }; // Channel a texture on image background class MagickDLLDecl textureImage : public std::unary_function { public: textureImage( const Image &texture_ ); void operator()( Image &image_ ) const; private: Image _texture; }; // Threshold image class MagickDLLDecl thresholdImage : public std::unary_function { public: thresholdImage( const double threshold_ ); void operator()( Image &image_ ) const; private: double _threshold; }; // Transform image based on image and crop geometries class MagickDLLDecl transformImage : public std::unary_function { public: transformImage( const Geometry &imageGeometry_ ); transformImage( const Geometry &imageGeometry_, const Geometry &cropGeometry_ ); void operator()( Image &image_ ) const; private: Geometry _imageGeometry; Geometry _cropGeometry; }; // Set image color to transparent class MagickDLLDecl transparentImage : public std::unary_function { public: transparentImage( const Color& color_ ); void operator()( Image &image_ ) const; private: Color _color; }; // Trim edges that are the background color from the image class MagickDLLDecl trimImage : public std::unary_function { public: trimImage( void ); void operator()( Image &image_ ) const; private: }; // Map image pixels to a sine wave class MagickDLLDecl waveImage : public std::unary_function { public: waveImage( const double amplitude_ = 25.0, const double wavelength_ = 150.0 ); void operator()( Image &image_ ) const; private: double _amplitude; double _wavelength; }; // Zoom image to specified size. class MagickDLLDecl zoomImage : public std::unary_function { public: zoomImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // // Function object image attribute accessors // // Anti-alias Postscript and TrueType fonts (default true) class MagickDLLDecl antiAliasImage : public std::unary_function { public: antiAliasImage( const bool flag_ ); void operator()( Image &image_ ) const; private: bool _flag; }; // Join images into a single multi-image file class MagickDLLDecl adjoinImage : public std::unary_function { public: adjoinImage( const bool flag_ ); void operator()( Image &image_ ) const; private: bool _flag; }; // Time in 1/100ths of a second which must expire before displaying // the next image in an animated sequence. class MagickDLLDecl animationDelayImage : public std::unary_function { public: animationDelayImage( const unsigned int delay_ ); void operator()( Image &image_ ) const; private: unsigned int _delay; }; // Number of iterations to loop an animation (e.g. Netscape loop // extension) for. class MagickDLLDecl animationIterationsImage : public std::unary_function { public: animationIterationsImage( const unsigned int iterations_ ); void operator()( Image &image_ ) const; private: unsigned int _iterations; }; // Image background color class MagickDLLDecl backgroundColorImage : public std::unary_function { public: backgroundColorImage( const Color &color_ ); void operator()( Image &image_ ) const; private: Color _color; }; // Name of texture image to tile onto the image background class MagickDLLDecl backgroundTextureImage : public std::unary_function { public: backgroundTextureImage( const std::string &backgroundTexture_ ); void operator()( Image &image_ ) const; private: std::string _backgroundTexture; }; // Image border color class MagickDLLDecl borderColorImage : public std::unary_function { public: borderColorImage( const Color &color_ ); void operator()( Image &image_ ) const; private: Color _color; }; // Text bounding-box base color (default none) class MagickDLLDecl boxColorImage : public std::unary_function { public: boxColorImage( const Color &boxColor_ ); void operator()( Image &image_ ) const; private: Color _boxColor; }; // Chromaticity blue primary point (e.g. x=0.15, y=0.06) class MagickDLLDecl chromaBluePrimaryImage : public std::unary_function { public: chromaBluePrimaryImage( const double x_, const double y_ ); void operator()( Image &image_ ) const; private: double _x; double _y; }; // Chromaticity green primary point (e.g. x=0.3, y=0.6) class MagickDLLDecl chromaGreenPrimaryImage : public std::unary_function { public: chromaGreenPrimaryImage( const double x_, const double y_ ); void operator()( Image &image_ ) const; private: double _x; double _y; }; // Chromaticity red primary point (e.g. x=0.64, y=0.33) class MagickDLLDecl chromaRedPrimaryImage : public std::unary_function { public: chromaRedPrimaryImage( const double x_, const double y_ ); void operator()( Image &image_ ) const; private: double _x; double _y; }; // Chromaticity white point (e.g. x=0.3127, y=0.329) class MagickDLLDecl chromaWhitePointImage : public std::unary_function { public: chromaWhitePointImage( const double x_, const double y_ ); void operator()( Image &image_ ) const; private: double _x; double _y; }; // Colors within this distance are considered equal class MagickDLLDecl colorFuzzImage : public std::unary_function { public: colorFuzzImage( const double fuzz_ ); void operator()( Image &image_ ) const; private: double _fuzz; }; // Color at colormap position index_ class MagickDLLDecl colorMapImage : public std::unary_function { public: colorMapImage( const unsigned int index_, const Color &color_ ); void operator()( Image &image_ ) const; private: unsigned int _index; Color _color; }; // Composition operator to be used when composition is implicitly used // (such as for image flattening). class MagickDLLDecl composeImage : public std::unary_function { public: composeImage( const CompositeOperator compose_ ); void operator()( Image &image_ ) const; private: CompositeOperator _compose; }; // Compression type class MagickDLLDecl compressTypeImage : public std::unary_function { public: compressTypeImage( const CompressionType compressType_ ); void operator()( Image &image_ ) const; private: CompressionType _compressType; }; // Vertical and horizontal resolution in pixels of the image class MagickDLLDecl densityImage : public std::unary_function { public: densityImage( const Geometry &geomery_ ); void operator()( Image &image_ ) const; private: Geometry _geomery; }; // Image depth (bits allocated to red/green/blue components) class MagickDLLDecl depthImage : public std::unary_function { public: depthImage( const unsigned int depth_ ); void operator()( Image &image_ ) const; private: unsigned int _depth; }; // Endianness (LSBEndian like Intel or MSBEndian like SPARC) for image // formats which support endian-specific options. class MagickDLLDecl endianImage : public std::unary_function { public: endianImage( const EndianType endian_ ); void operator()( Image &image_ ) const; private: EndianType _endian; }; // Image file name class MagickDLLDecl fileNameImage : public std::unary_function { public: fileNameImage( const std::string &fileName_ ); void operator()( Image &image_ ) const; private: std::string _fileName; }; // Filter to use when resizing image class MagickDLLDecl filterTypeImage : public std::unary_function { public: filterTypeImage( const FilterTypes filterType_ ); void operator()( Image &image_ ) const; private: FilterTypes _filterType; }; // Text rendering font class MagickDLLDecl fontImage : public std::unary_function { public: fontImage( const std::string &font_ ); void operator()( Image &image_ ) const; private: std::string _font; }; // Font point size class MagickDLLDecl fontPointsizeImage : public std::unary_function { public: fontPointsizeImage( const unsigned int pointsize_ ); void operator()( Image &image_ ) const; private: unsigned int _pointsize; }; // GIF disposal method class MagickDLLDecl gifDisposeMethodImage : public std::unary_function { public: gifDisposeMethodImage( const unsigned int disposeMethod_ ); void operator()( Image &image_ ) const; private: unsigned int _disposeMethod; }; // Type of interlacing to use class MagickDLLDecl interlaceTypeImage : public std::unary_function { public: interlaceTypeImage( const InterlaceType interlace_ ); void operator()( Image &image_ ) const; private: InterlaceType _interlace; }; // Linewidth for drawing vector objects (default one) class MagickDLLDecl lineWidthImage : public std::unary_function { public: lineWidthImage( const double lineWidth_ ); void operator()( Image &image_ ) const; private: double _lineWidth; }; // File type magick identifier (.e.g "GIF") class MagickDLLDecl magickImage : public std::unary_function { public: magickImage( const std::string &magick_ ); void operator()( Image &image_ ) const; private: std::string _magick; }; // Image supports transparent color class MagickDLLDecl matteImage : public std::unary_function { public: matteImage( const bool matteFlag_ ); void operator()( Image &image_ ) const; private: bool _matteFlag; }; // Transparent color class MagickDLLDecl matteColorImage : public std::unary_function { public: matteColorImage( const Color &matteColor_ ); void operator()( Image &image_ ) const; private: Color _matteColor; }; // Indicate that image is black and white class MagickDLLDecl monochromeImage : public std::unary_function { public: monochromeImage( const bool monochromeFlag_ ); void operator()( Image &image_ ) const; private: bool _monochromeFlag; }; // Pen color class MagickDLLDecl penColorImage : public std::unary_function { public: penColorImage( const Color &penColor_ ); void operator()( Image &image_ ) const; private: Color _penColor; }; // Pen texture image. class MagickDLLDecl penTextureImage : public std::unary_function { public: penTextureImage( const Image &penTexture_ ); void operator()( Image &image_ ) const; private: Image _penTexture; }; // Set pixel color at location x & y. class MagickDLLDecl pixelColorImage : public std::unary_function { public: pixelColorImage( const unsigned int x_, const unsigned int y_, const Color &color_); void operator()( Image &image_ ) const; private: unsigned int _x; unsigned int _y; Color _color; }; // Postscript page size. class MagickDLLDecl pageImage : public std::unary_function { public: pageImage( const Geometry &pageSize_ ); void operator()( Image &image_ ) const; private: Geometry _pageSize; }; // JPEG/MIFF/PNG compression level (default 75). class MagickDLLDecl qualityImage : public std::unary_function { public: qualityImage( const unsigned int quality_ ); void operator()( Image &image_ ) const; private: unsigned int _quality; }; // Maximum number of colors to quantize to class MagickDLLDecl quantizeColorsImage : public std::unary_function { public: quantizeColorsImage( const unsigned int colors_ ); void operator()( Image &image_ ) const; private: unsigned int _colors; }; // Colorspace to quantize in. class MagickDLLDecl quantizeColorSpaceImage : public std::unary_function { public: quantizeColorSpaceImage( const ColorspaceType colorSpace_ ); void operator()( Image &image_ ) const; private: ColorspaceType _colorSpace; }; // Dither image during quantization (default true). class MagickDLLDecl quantizeDitherImage : public std::unary_function { public: quantizeDitherImage( const bool ditherFlag_ ); void operator()( Image &image_ ) const; private: bool _ditherFlag; }; // Quantization tree-depth class MagickDLLDecl quantizeTreeDepthImage : public std::unary_function { public: quantizeTreeDepthImage( const unsigned int treeDepth_ ); void operator()( Image &image_ ) const; private: unsigned int _treeDepth; }; // The type of rendering intent class MagickDLLDecl renderingIntentImage : public std::unary_function { public: renderingIntentImage( const RenderingIntent renderingIntent_ ); void operator()( Image &image_ ) const; private: RenderingIntent _renderingIntent; }; // Units of image resolution class MagickDLLDecl resolutionUnitsImage : public std::unary_function { public: resolutionUnitsImage( const ResolutionType resolutionUnits_ ); void operator()( Image &image_ ) const; private: ResolutionType _resolutionUnits; }; // Image scene number class MagickDLLDecl sceneImage : public std::unary_function { public: sceneImage( const unsigned int scene_ ); void operator()( Image &image_ ) const; private: unsigned int _scene; }; // Width and height of a raw image class MagickDLLDecl sizeImage : public std::unary_function { public: sizeImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Subimage of an image sequence class MagickDLLDecl subImageImage : public std::unary_function { public: subImageImage( const unsigned int subImage_ ); void operator()( Image &image_ ) const; private: unsigned int _subImage; }; // Number of images relative to the base image class MagickDLLDecl subRangeImage : public std::unary_function { public: subRangeImage( const unsigned int subRange_ ); void operator()( Image &image_ ) const; private: unsigned int _subRange; }; // Tile name class MagickDLLDecl tileNameImage : public std::unary_function { public: tileNameImage( const std::string &tileName_ ); void operator()( Image &image_ ) const; private: std::string _tileName; }; // Image storage type class MagickDLLDecl typeImage : public std::unary_function { public: typeImage( const ImageType type_ ); void operator()( Image &image_ ) const; private: Magick::ImageType _type; }; // Print detailed information about the image class MagickDLLDecl verboseImage : public std::unary_function { public: verboseImage( const bool verbose_ ); void operator()( Image &image_ ) const; private: bool _verbose; }; // FlashPix viewing parameters class MagickDLLDecl viewImage : public std::unary_function { public: viewImage( const std::string &view_ ); void operator()( Image &image_ ) const; private: std::string _view; }; // X11 display to display to, obtain fonts from, or to capture // image from class MagickDLLDecl x11DisplayImage : public std::unary_function { public: x11DisplayImage( const std::string &display_ ); void operator()( Image &image_ ) const; private: std::string _display; }; ////////////////////////////////////////////////////////// // // Implementation template definitions. Not for end-use. // ////////////////////////////////////////////////////////// // Link images together into an image list based on the ordering of // the container implied by the iterator. This step is done in // preparation for use with ImageMagick functions which operate on // lists of images. // Images are selected by range, first_ to last_ so that a subset of // the container may be selected. Specify first_ via the // container's begin() method and last_ via the container's end() // method in order to specify the entire container. template void linkImages( InputIterator first_, InputIterator last_ ) { MagickLib::Image* previous = 0; int scene = 0; for ( InputIterator iter = first_; iter != last_; ++iter ) { // Unless we reduce the reference count to one, the same image // structure may occur more than once in the container, causing // the linked list to fail. iter->modifyImage(); MagickLib::Image* current = iter->image(); current->previous = previous; current->next = 0; current->scene = scene++; if ( previous != 0) previous->next = current; previous = current; } } // Remove links added by linkImages. This should be called after the // ImageMagick function call has completed to reset the image list // back to its pristine un-linked state. template void unlinkImages( InputIterator first_, InputIterator last_ ) { for( InputIterator iter = first_; iter != last_; ++iter ) { MagickLib::Image* image = iter->image(); image->previous = 0; image->next = 0; } } // Insert images in image list into existing container (appending to container) // The images should not be deleted since only the image ownership is passed. // The options are copied into the object. template void insertImages( Container *sequence_, MagickLib::Image* images_ ) { MagickLib::Image *image = images_; if ( image ) { do { MagickLib::Image* next_image = image->next; image->next = 0; if (next_image != 0) next_image->previous=0; sequence_->push_back( Magick::Image( image ) ); image=next_image; } while( image ); return; } } /////////////////////////////////////////////////////////////////// // // Template definitions for documented API // /////////////////////////////////////////////////////////////////// template void animateImages( InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::AnimateImages( first_->imageInfo(), first_->image() ); MagickLib::GetImageException( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } // Append images from list into single image in either horizontal or // vertical direction. template void appendImages( Image *appendedImage_, InputIterator first_, InputIterator last_, bool stack_ = false) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::Image* image = MagickLib::AppendImages( first_->image(), stack_, &exceptionInfo ); unlinkImages( first_, last_ ); appendedImage_->replaceImage( image ); throwException( exceptionInfo, appendedImage_->quiet() ); } // Average a set of images. // All the input images must be the same size in pixels. template void averageImages( Image *averagedImage_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::Image* image = MagickLib::AverageImages( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); averagedImage_->replaceImage( image ); throwException( exceptionInfo, averagedImage_->quiet() ); } // Merge a sequence of images. // This is useful for GIF animation sequences that have page // offsets and disposal methods. A container to contain // the updated image sequence is passed via the coalescedImages_ // option. template void coalesceImages( Container *coalescedImages_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); // Build image list linkImages( first_, last_ ); MagickLib::Image* images = MagickLib::CoalesceImages( first_->image(), &exceptionInfo); // Unlink image list unlinkImages( first_, last_ ); // Ensure container is empty coalescedImages_->clear(); // Move images to container insertImages( coalescedImages_, images ); // Report any error throwException( exceptionInfo, first_->quiet() ); } // Return format coders matching specified conditions. // // The default (if no match terms are supplied) is to return all // available format coders. // // For example, to return all readable formats: // list coderList; // coderInfoList( &coderList, CoderInfo::TrueMatch, CoderInfo::AnyMatch, CoderInfo::AnyMatch) // template void coderInfoList( Container *container_, CoderInfo::MatchType isReadable_ = CoderInfo::AnyMatch, CoderInfo::MatchType isWritable_ = CoderInfo::AnyMatch, CoderInfo::MatchType isMultiFrame_ = CoderInfo::AnyMatch ) { // Obtain first entry in MagickInfo list MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); MagickLib::MagickInfo **coder_list = MagickLib::GetMagickInfoArray( &exceptionInfo ); if( !coder_list ) { throwException( exceptionInfo ); throwExceptionExplicit(MagickLib::MissingDelegateError, "Coder array not returned!", 0 ); } // Clear out container container_->clear(); for ( int i=0; coder_list[i] != 0; i++) { // Skip stealth coders if ( coder_list[i]->stealth ) continue; try { CoderInfo coderInfo( coder_list[i]->name ); // Test isReadable_ if ( isReadable_ != CoderInfo::AnyMatch && (( coderInfo.isReadable() && isReadable_ != CoderInfo::TrueMatch ) || ( !coderInfo.isReadable() && isReadable_ != CoderInfo::FalseMatch )) ) continue; // Test isWritable_ if ( isWritable_ != CoderInfo::AnyMatch && (( coderInfo.isWritable() && isWritable_ != CoderInfo::TrueMatch ) || ( !coderInfo.isWritable() && isWritable_ != CoderInfo::FalseMatch )) ) continue; // Test isMultiFrame_ if ( isMultiFrame_ != CoderInfo::AnyMatch && (( coderInfo.isMultiFrame() && isMultiFrame_ != CoderInfo::TrueMatch ) || ( !coderInfo.isMultiFrame() && isMultiFrame_ != CoderInfo::FalseMatch )) ) continue; // Append matches to container container_->push_back( coderInfo ); } // Intentionally ignore missing module errors catch ( Magick::ErrorModule & ) { continue; } } MagickLib::MagickFree(coder_list); coder_list=0; MagickLib::DestroyExceptionInfo( &exceptionInfo ); } // // Fill container with color histogram. // Entries are of type "std::pair". Use the pair // "first" member to access the Color and the "second" member to access // the number of times the color occurs in the image. // // For example: // // Using : // // Image image("image.miff"); // map histogram; // colorHistogram( &histogram, image ); // std::map::const_iterator p=histogram.begin(); // while (p != histogram.end()) // { // cout << setw(10) << (int)p->second << ": (" // << setw(quantum_width) << (int)p->first.redQuantum() << "," // << setw(quantum_width) << (int)p->first.greenQuantum() << "," // << setw(quantum_width) << (int)p->first.blueQuantum() << ")" // << endl; // p++; // } // // Using : // // Image image("image.miff"); // std::vector > histogram; // colorHistogram( &histogram, image ); // std::vector >::const_iterator p=histogram.begin(); // while (p != histogram.end()) // { // cout << setw(10) << (int)p->second << ": (" // << setw(quantum_width) << (int)p->first.redQuantum() << "," // << setw(quantum_width) << (int)p->first.greenQuantum() << "," // << setw(quantum_width) << (int)p->first.blueQuantum() << ")" // << endl; // p++; // } template void colorHistogram( Container *histogram_, const Image image) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); // Obtain histogram array unsigned long colors; MagickLib::HistogramColorPacket *histogram_array = MagickLib::GetColorHistogram( image.constImage(), &colors, &exceptionInfo ); throwException( exceptionInfo, image.quiet() ); // Clear out container histogram_->clear(); // Transfer histogram array to container for ( unsigned long i=0; i < colors; i++) { histogram_->insert(histogram_->end(),std::pair ( Color(histogram_array[i].pixel.red, histogram_array[i].pixel.green, histogram_array[i].pixel.blue), histogram_array[i].count) ); } // Deallocate histogram array MagickLib::MagickFree(histogram_array); histogram_array = 0; } // Break down an image sequence into constituent parts. This is // useful for creating GIF or MNG animation sequences. template void deconstructImages( Container *deconstructedImages_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); // Build image list linkImages( first_, last_ ); MagickLib::Image* images = MagickLib::DeconstructImages( first_->image(), &exceptionInfo); // Unlink image list unlinkImages( first_, last_ ); // Ensure container is empty deconstructedImages_->clear(); // Move images to container insertImages( deconstructedImages_, images ); // Report any error throwException( exceptionInfo, first_->quiet() ); } // // Display an image sequence // template void displayImages( InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::DisplayImages( first_->imageInfo(), first_->image() ); MagickLib::GetImageException( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } // Merge a sequence of image frames which represent image layers. // This is useful for combining Photoshop layers into a single image. template void flattenImages( Image *flattendImage_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::Image* image = MagickLib::FlattenImages( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); flattendImage_->replaceImage( image ); throwException( exceptionInfo, flattendImage_->quiet() ); } // Replace the colors of a sequence of images with the closest color // from a reference image. // Set dither_ to true to enable dithering. Set measureError_ to // true in order to evaluate quantization error. template void mapImages( InputIterator first_, InputIterator last_, const Image& mapImage_, bool dither_ = false, bool measureError_ = false ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::MapImages( first_->image(), mapImage_.constImage(), dither_ ); MagickLib::GetImageException( first_->image(), &exceptionInfo ); if ( exceptionInfo.severity != MagickLib::UndefinedException ) { unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } MagickLib::Image* image = first_->image(); while( image ) { // Calculate quantization error if ( measureError_ ) { MagickLib::GetImageQuantizeError( image ); if ( image->exception.severity > MagickLib::UndefinedException ) { unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } } // Udate DirectClass representation of pixels MagickLib::SyncImage( image ); if ( image->exception.severity > MagickLib::UndefinedException ) { unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } // Next image image=image->next; } unlinkImages( first_, last_ ); } // Create a composite image by combining several separate images. template void montageImages( Container *montageImages_, InputIterator first_, InputIterator last_, const Montage &montageOpts_ ) { MagickLib::MontageInfo* montageInfo = static_cast(MagickLib::MagickMalloc(sizeof(MagickLib::MontageInfo))); // Update montage options with those set in montageOpts_ montageOpts_.updateMontageInfo( *montageInfo ); // Update options which must transfer to image options if ( montageOpts_.label().length() != 0 ) first_->label( montageOpts_.label() ); // Create linked image list linkImages( first_, last_ ); // Reset output container to pristine state montageImages_->clear(); // Do montage MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); MagickLib::Image *images = MagickLib::MontageImages( first_->image(), montageInfo, &exceptionInfo ); if ( images != 0 ) { insertImages( montageImages_, images ); } // Clean up any allocated data in montageInfo MagickLib::DestroyMontageInfo( montageInfo ); // Unlink linked image list unlinkImages( first_, last_ ); // Report any montage error throwException( exceptionInfo, first_->quiet() ); // Apply transparency to montage images if ( montageImages_->size() > 0 && montageOpts_.transparentColor().isValid() ) { for_each( first_, last_, transparentImage( montageOpts_.transparentColor() ) ); } // Report any transparentImage() error MagickLib::GetImageException( first_->image(), &exceptionInfo ); throwException( exceptionInfo, first_->quiet() ); } // Morph a set of images template void morphImages( Container *morphedImages_, InputIterator first_, InputIterator last_, unsigned int frames_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); // Build image list linkImages( first_, last_ ); MagickLib::Image* images = MagickLib::MorphImages( first_->image(), frames_, &exceptionInfo); // Unlink image list unlinkImages( first_, last_ ); // Ensure container is empty morphedImages_->clear(); // Move images to container insertImages( morphedImages_, images ); // Report any error throwException( exceptionInfo, first_->quiet() ); } // Inlay a number of images to form a single coherent picture. template void mosaicImages( Image *mosaicImage_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::Image* image = MagickLib::MosaicImages( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); mosaicImage_->replaceImage( image ); throwException( exceptionInfo, first_->quiet() ); } // Quantize colors in images using current quantization settings // Set measureError_ to true in order to measure quantization error template void quantizeImages( InputIterator first_, InputIterator last_, bool measureError_ = false ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::QuantizeImages( first_->quantizeInfo(), first_->image() ); MagickLib::GetImageException( first_->image(), &exceptionInfo ); if ( exceptionInfo.severity > MagickLib::UndefinedException ) { unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } MagickLib::Image* image = first_->image(); while( image != 0 ) { // Calculate quantization error if ( measureError_ ) MagickLib::GetImageQuantizeError( image ); // Update DirectClass representation of pixels MagickLib::SyncImage( image ); // Next image image=image->next; } unlinkImages( first_, last_ ); } // Read images into existing container (appending to container) // FIXME: need a way to specify options like size, depth, and density. template void readImages( Container *sequence_, const std::string &imageSpec_ ) { MagickLib::ImageInfo *imageInfo = MagickLib::CloneImageInfo(0); imageSpec_.copy( imageInfo->filename, MaxTextExtent-1 ); imageInfo->filename[ imageSpec_.length() ] = 0; MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); MagickLib::Image* images = MagickLib::ReadImage( imageInfo, &exceptionInfo ); MagickLib::DestroyImageInfo(imageInfo); insertImages( sequence_, images); throwException( exceptionInfo ); } template void readImages( Container *sequence_, const Blob &blob_ ) { MagickLib::ImageInfo *imageInfo = MagickLib::CloneImageInfo(0); MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); MagickLib::Image *images = MagickLib::BlobToImage( imageInfo, blob_.data(), blob_.length(), &exceptionInfo ); MagickLib::DestroyImageInfo(imageInfo); insertImages( sequence_, images ); throwException( exceptionInfo ); } // Write Images // // If an attribute is not supported as an explicit argument // (e.g. 'magick'), then the attribute must be set on the involved // images in the container prior to invoking writeImages() since // attributes from the individual images are the ones which are // used. template void writeImages( InputIterator first_, InputIterator last_, const std::string &imageSpec_, bool adjoin_ = true ) { first_->adjoin( adjoin_ ); MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); int errorStat = MagickLib::WriteImages( first_->constImageInfo(), first_->image(), imageSpec_.c_str(), &exceptionInfo ); unlinkImages( first_, last_ ); if ( errorStat != false ) { MagickLib::DestroyExceptionInfo( &exceptionInfo ); return; } throwException( exceptionInfo, first_->quiet() ); } // Write images to BLOB // // If an attribute is not supported as an explicit argument // (e.g. 'magick'), then the attribute must be set on the involved // images in the container prior to invoking writeImages() since // attributes from the individual images are the ones which are // used. template void writeImages( InputIterator first_, InputIterator last_, Blob *blob_, bool adjoin_ = true) { first_->adjoin( adjoin_ ); linkImages( first_, last_ ); MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); size_t length = 2048; // Efficient size for small images void* data = MagickLib::ImageToBlob( first_->imageInfo(), first_->image(), &length, &exceptionInfo); blob_->updateNoCopy( data, length, Magick::Blob::MallocAllocator ); unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } } // namespace Magick #endif // Magick_STL_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++/TypeMetric.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 2001, 2002 // // TypeMetric Definition // // Container for font type metrics // #if !defined (Magick_TypeMetric_header) #define Magick_TypeMetric_header #include "Magick++/Include.h" namespace Magick { class MagickDLLDecl TypeMetric { friend class Image; public: TypeMetric ( void ); ~TypeMetric ( void ); // Ascent, the distance in pixels from the text baseline to the // highest/upper grid coordinate used to place an outline point. double ascent ( void ) const; // Descent, the distance in pixels from the baseline to the lowest // grid coordinate used to place an outline point. Always a // negative value. double descent ( void ) const; // Text width in pixels. double textWidth ( void ) const; // Text height in pixels. double textHeight ( void ) const; // Maximum horizontal advance in pixels. double maxHorizontalAdvance ( void ) const; // // Public methods below this point are for Magick++ use only. // private: MagickLib::TypeMetric _typeMetric; }; } // namespace Magick // // Inlines // #endif // Magick_TypeMetric_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/Magick++.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000 // // Simplified includes for Magick++. // Inclusion of this header is sufficient to use all Magick++ APIs. // #ifndef MagickPlusPlus_Header #include #include #include #include #define MagickPlusPlus_Header #endif // MagickPlusPlus_Header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/analyze.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Analysis Methods. */ #ifndef _MAGICK_ANALYZE_H #define _MAGICK_ANALYZE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ #include "magick/image.h" typedef struct _ImageCharacteristics { MagickBool cmyk, /* CMYK(A) image */ grayscale, /* Grayscale image */ monochrome, /* Black/white image */ opaque, /* Opaque image */ palette; /* Colormapped image */ } ImageCharacteristics; /* Functions which return unsigned int to indicate operation pass/fail */ extern MagickExport MagickPassFail GetImageCharacteristics(const Image *image,ImageCharacteristics *characteristics, const MagickBool optimize,ExceptionInfo *exception); extern MagickExport unsigned long GetImageDepth(const Image *,ExceptionInfo *); extern MagickExport MagickBool IsGrayImage(const Image *image,ExceptionInfo *exception), IsMonochromeImage(const Image *image,ExceptionInfo *exception), IsOpaqueImage(const Image *image,ExceptionInfo *exception); extern MagickExport ImageType GetImageType(const Image *,ExceptionInfo *); extern MagickExport RectangleInfo GetImageBoundingBox(const Image *,ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_ANALYZE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/api.h ================================================ /* Copyright (C) 2003 - 2012 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Application Programming Interface declarations. */ #if !defined(_MAGICK_API_H) #define _MAGICK_API_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/magick_config.h" #if defined(__cplusplus) || defined(c_plusplus) # undef inline #endif #include #include #include #include /* POSIX 1990 header and declares size_t and ssize_t */ /* Note that the WIN32 and WIN64 definitions are provided by the build configuration rather than the compiler. Definitions available from the Windows compiler are _WIN32 and _WIN64. */ #if defined(WIN32) || defined(WIN64) # define MSWINDOWS #endif /* defined(WIN32) || defined(WIN64) */ #if defined(MAGICK_IMPLEMENTATION) # if defined(MSWINDOWS) /* Use Visual C++ C inline method extension to improve performance */ # if !defined(inline) && !defined(__cplusplus) && !defined(c_plusplus) # define inline __inline # endif # endif #endif #if defined(PREFIX_MAGICK_SYMBOLS) # include "magick/symbols.h" #endif /* defined(PREFIX_MAGICK_SYMBOLS) */ #include "magick/common.h" #include "magick/magick_types.h" #include "magick/analyze.h" #include "magick/attribute.h" #include "magick/average.h" #include "magick/blob.h" #include "magick/cdl.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color_lookup.h" #include "magick/colormap.h" #include "magick/command.h" #include "magick/compare.h" #include "magick/composite.h" #include "magick/compress.h" #include "magick/confirm_access.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/delegate.h" #include "magick/deprecate.h" #include "magick/describe.h" #include "magick/draw.h" #include "magick/effect.h" #include "magick/enhance.h" #include "magick/error.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/gradient.h" #include "magick/hclut.h" #include "magick/image.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/montage.h" #include "magick/operator.h" #include "magick/paint.h" #include "magick/pixel_cache.h" #include "magick/pixel_iterator.h" #include "magick/plasma.h" #include "magick/profile.h" #include "magick/quantize.h" /*#include "magick/random.h"*/ #include "magick/registry.h" #include "magick/render.h" #include "magick/resize.h" #include "magick/resource.h" #include "magick/shear.h" #include "magick/signature.h" #include "magick/statistics.h" #include "magick/texture.h" #include "magick/timer.h" #include "magick/transform.h" #include "magick/type.h" #include "magick/utility.h" #include "magick/version.h" #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_API_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/attribute.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Methods to Get/Set/Destroy Image Text Attributes. */ #ifndef _MAGICK_ATTRIBUTE_H #define _MAGICK_ATTRIBUTE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/image.h" typedef struct _ImageAttribute { char *key, /* identifying key */ *value; /* value string */ size_t length; /* value string length */ struct _ImageAttribute *previous, *next; } ImageAttribute; /* MagickExported text attribute methods. */ extern MagickExport const ImageAttribute *GetImageAttribute(const Image *image,const char *key), *GetImageClippingPathAttribute(const Image *image), *GetImageInfoAttribute(const ImageInfo *image_info,const Image *image,const char *key); extern MagickExport MagickPassFail CloneImageAttributes(Image* clone_image, const Image* original_image), SetImageAttribute(Image *image,const char *key,const char *value); extern MagickExport void DestroyImageAttributes(Image *image); #if defined(MAGICK_IMPLEMENTATION) # include "magick/attribute-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/average.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Averaging Methods. */ #ifndef _MAGICK_AVERAGE_H #define _MAGICK_AVERAGE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" extern MagickExport Image *AverageImages(const Image *,ExceptionInfo *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_AVERAGE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/blob.h ================================================ /* Copyright (C) 2003-2018 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Image Compression/Decompression Methods. */ #ifndef _MAGICK_BLOB_H #define _MAGICK_BLOB_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/image.h" /* Minimum input file size before considering for memory map. */ #define MinBlobExtent 32768L /* Forward declarations. */ typedef struct _BlobInfo BlobInfo; /* * * BlobInfo methods * */ /* Makes a duplicate of the given blob info structure, or if blob info is NULL, a new one. */ extern MagickExport BlobInfo* CloneBlobInfo(const BlobInfo *blob_info); /* Increments the reference count associated with the pixel blob, returning a pointer to the blob. */ extern MagickExport BlobInfo* ReferenceBlob(BlobInfo *blob); /* Deallocate memory associated with the BlobInfo structure. */ extern MagickExport void DestroyBlobInfo(BlobInfo *blob) MAGICK_FUNC_DEPRECATED; /* If BLOB is a memory mapping then unmap it. Reset BlobInfo structure to its default state. */ extern MagickExport void DetachBlob(BlobInfo *blob); /* Initialize a BlobInfo structure. */ extern MagickExport void GetBlobInfo(BlobInfo *blob); /* Attach memory buffer to a BlobInfo structure. */ extern MagickExport void AttachBlob(BlobInfo *blob_info, const void *blob, const size_t length); /* * * Functions for managing a BLOB (type BlobInfo) attached to an Image. * */ /* Deallocate all memory associated with an Image blob (reference counted). */ extern MagickExport void DestroyBlob(Image *image); /* * * Formatted image I/O functions * */ /* Read an Image from a formatted in-memory "file" image ("BLOB"). */ extern MagickExport Image* BlobToImage(const ImageInfo *image_info, const void *blob, const size_t length, ExceptionInfo *exception); /* Return an Image populated with salient information regarding a formatted in-memory "file" image ("BLOB") but without reading the image pixels. */ extern MagickExport Image* PingBlob(const ImageInfo *image_info, const void *blob, const size_t length, ExceptionInfo *exception); /* Writes an Image to a formatted (like a file) in-memory representation. */ extern MagickExport void *ImageToBlob(const ImageInfo *image_info, Image *image, size_t *length, ExceptionInfo *exception); /* * * Core File or BLOB I/O functions. * */ /* Blob open modes. */ typedef enum { UndefinedBlobMode, /* Undefined */ ReadBlobMode, /* Open for reading (text) */ /* only locale.c */ ReadBinaryBlobMode, /* Open for reading (binary) */ WriteBlobMode, /* Open for writing (text) */ /* only mvg.c txt.c */ WriteBinaryBlobMode /* Open for writing (binary) */ } BlobMode; /* Open an input or output stream for access. May also use a stream provided via image_info->stream. */ extern MagickExport MagickPassFail OpenBlob(const ImageInfo *image_info, Image *image, const BlobMode mode, ExceptionInfo *exception); /* Close I/O to the file or BLOB. */ extern MagickExport MagickPassFail CloseBlob(Image *image); /* Read data from the file or BLOB into a buffer. */ extern MagickExport size_t ReadBlob(Image *image, const size_t length, void *data); /* Read data from the file or BLOB into a buffer, but support zero-copy if possible. */ extern MagickExport size_t ReadBlobZC(Image *image, const size_t length, void **data); /* Write data from a buffer to the file or BLOB. */ extern MagickExport size_t WriteBlob(Image *image, const size_t length, const void *data); /* Move the current read or write offset position in the file or BLOB. */ extern MagickExport magick_off_t SeekBlob(Image *image, const magick_off_t offset, const int whence); /* Obtain the current read or write offset position in the file or BLOB. */ extern MagickExport magick_off_t TellBlob(const Image *image); /* Test to see if EOF has been detected while reading the file or BLOB. */ extern MagickExport int EOFBlob(const Image *image); /* Test to see if an error has been encountered while doing I/O to the file or BLOB. Non-zero is returned if an error occured. */ extern MagickExport int GetBlobStatus(const Image *image) MAGICK_FUNC_PURE; /* Return the first errno present when an error has been encountered while doing I/O to the file or BLOB. This is only useful if GetBlobStatus() has already reported that an error occured. */ extern MagickExport int GetBlobFirstErrno(const Image *image) MAGICK_FUNC_PURE; /* Test to see if blob is currently open. */ extern MagickExport MagickBool GetBlobIsOpen(const Image *image) MAGICK_FUNC_PURE; /* Obtain the current size of the file or BLOB. Zero is returned if the size can not be determined. If BLOB is no longer open, then return the size when the BLOB was closed. */ extern MagickExport magick_off_t GetBlobSize(const Image *image); /* Obtain the underlying stdio FILE* for the file (if any). */ extern MagickExport FILE *GetBlobFileHandle(const Image *image) MAGICK_FUNC_PURE; /* Obtain a pointer to the base of where BLOB data is stored. The data is only available if the data is stored on the heap, or is memory mapped. Otherwise NULL is returned. */ extern MagickExport unsigned char *GetBlobStreamData(const Image *image) MAGICK_FUNC_PURE; /* * * Formatted File or BLOB I/O functions. * */ /* Read a single byte from the file or BLOB. Returns an EOF character if EOF has been detected. */ extern MagickExport int ReadBlobByte(Image *image); /* Read a 16-bit little-endian unsigned "short" value from the file or BLOB. */ extern MagickExport magick_uint16_t ReadBlobLSBShort(Image *image); /* Read a 16-bit little-endian signed "short" value from the file or BLOB. */ extern MagickExport magick_int16_t ReadBlobLSBSignedShort(Image *image); /* Read an array of little-endian unsigned 16-bit "short" values from the file or BLOB. */ extern MagickExport size_t ReadBlobLSBShorts(Image *image, size_t octets, magick_uint16_t *data); /* Read a 16-bit big-endian unsigned "short" value from the file or BLOB. */ extern MagickExport magick_uint16_t ReadBlobMSBShort(Image *image); /* Read a 16-bit big-endian signed "short" value from the file or BLOB. */ extern MagickExport magick_int16_t ReadBlobMSBSignedShort(Image *image); /* Read an array of big-endian 16-bit "short" values from the file or BLOB. */ extern MagickExport size_t ReadBlobMSBShorts(Image *image, size_t octets, magick_uint16_t *data); /* Read a 32-bit little-endian unsigned "long" value from the file or BLOB. */ extern MagickExport magick_uint32_t ReadBlobLSBLong(Image *image); /* Read a 32-bit little-endian signed "long" value from the file or BLOB. */ extern MagickExport magick_int32_t ReadBlobLSBSignedLong(Image *image); /* Read an array of little-endian 32-bit "long" values from the file or BLOB. */ extern MagickExport size_t ReadBlobLSBLongs(Image *image, size_t octets, magick_uint32_t *data); /* Read a 32-bit big-endian unsigned "long" value from the file or BLOB. */ extern MagickExport magick_uint32_t ReadBlobMSBLong(Image *image); /* Read a 32-bit big-endian signed "long" value from the file or BLOB. */ extern MagickExport magick_int32_t ReadBlobMSBSignedLong(Image *image); /* Read an array of big-endian 32-bit "long" values from the file or BLOB. */ extern MagickExport size_t ReadBlobMSBLongs(Image *image, size_t octets, magick_uint32_t *data); /* Read a little-endian 32-bit "float" value from the file or BLOB. */ extern MagickExport float ReadBlobLSBFloat(Image *image); /* Read an array of little-endian 32-bit "float" values from the file or BLOB. */ extern MagickExport size_t ReadBlobLSBFloats(Image *image, size_t octets, float *data); /* Read a big-endian 32-bit "float" value from the file or BLOB. */ extern MagickExport float ReadBlobMSBFloat(Image *image); /* Read an array of big-endian 32-bit "float" values from the file or BLOB. */ extern MagickExport size_t ReadBlobMSBFloats(Image *image, size_t octets, float *data); /* Read a little-endian 64-bit "double" value from the file or BLOB. */ extern MagickExport double ReadBlobLSBDouble(Image *image); /* Read an array of little-endian 64-bit "double" values from the file or BLOB. */ extern MagickExport size_t ReadBlobLSBDoubles(Image *image, size_t octets, double *data); /* Read a big-endian 64-bit "double" value from the file or BLOB. */ extern MagickExport double ReadBlobMSBDouble(Image *image); /* Read an array of big-endian 64-bit "double" values from the file or BLOB. */ extern MagickExport size_t ReadBlobMSBDoubles(Image *image, size_t octets, double *data); /* Read a string from the file or blob until a newline character is read or an end-of-file condition is encountered. */ extern MagickExport char *ReadBlobString(Image *image, char *string); /* Write a single byte to the file or BLOB. */ extern MagickExport size_t WriteBlobByte(Image *image, const magick_uint8_t value); /* Write the content of an entire disk file to the file or BLOB. */ extern MagickExport MagickPassFail WriteBlobFile(Image *image, const char *filename); /* Write a 16-bit signed "short" value to the file or BLOB in little-endian order. */ extern MagickExport size_t WriteBlobLSBShort(Image *image, const magick_uint16_t value); /* Write a 16-bit signed "short" value to the file or BLOB in little-endian order. */ extern MagickExport size_t WriteBlobLSBSignedShort(Image *image, const magick_int16_t value); /* Write a 32-bit unsigned "long" value to the file or BLOB in little-endian order. */ extern MagickExport size_t WriteBlobLSBLong(Image *image, const magick_uint32_t value); /* Write a 32-bit signed "long" value to the file or BLOB in little-endian order. */ extern MagickExport size_t WriteBlobLSBSignedLong(Image *image, const magick_int32_t value); /* Write a 32-bit unsigned "long" value to the file or BLOB in big-endian order. */ extern MagickExport size_t WriteBlobMSBLong(Image *image, const magick_uint32_t value); /* Write a 32-bit signed "long" value to the file or BLOB in big-endian order. */ extern MagickExport size_t WriteBlobMSBSignedLong(Image *image, const magick_int32_t value); /* Write a 16-bit unsigned "short" value to the file or BLOB in big-endian order. */ extern MagickExport size_t WriteBlobMSBShort(Image *image, const magick_uint16_t value); /* Write a 16-bit signed "short" value to the file or BLOB in big-endian order. */ extern MagickExport size_t WriteBlobMSBSignedShort(Image *image, const magick_int16_t value); /* Write a C string to the file or BLOB, without the terminating NULL byte. */ extern MagickExport size_t WriteBlobString(Image *image, const char *string); /* * * BLOB attribute access. * */ /* Blob supports seek operations. BlobSeek() and BlobTell() may safely be used. */ extern MagickExport MagickBool BlobIsSeekable(const Image *image) MAGICK_FUNC_PURE; /* Allow file descriptor to be closed (if True). */ extern MagickExport void SetBlobClosable(Image *image, MagickBool closable); /* Blob is for a temporary file which should be deleted (if True). */ extern MagickExport void SetBlobTemporary(Image *image, MagickBool isTemporary); /* Returns MagickTrue if the file associated with the blob is a temporary file and should be removed when the associated image is destroyed. */ extern MagickExport MagickBool GetBlobTemporary(const Image *image) MAGICK_FUNC_PURE; /* * * Memory mapped file support. * */ /* Memory mapping modes. */ typedef enum { ReadMode, /* Map for read-only access */ WriteMode, /* Map for write-only access (useless) */ IOMode /* Map for read/write access */ } MapMode; /* Release memory mapping for a region. */ extern MagickExport MagickPassFail UnmapBlob(void *map, const size_t length); /* Perform a requested memory mapping of a file descriptor. */ extern MagickExport void *MapBlob(int file, const MapMode mode, magick_off_t offset, size_t length); /* * * Buffer to File / File to Buffer functions. * */ /* Writes a buffer to a named file. */ extern MagickExport MagickPassFail BlobToFile(const char *filename, const void *blob, const size_t length, ExceptionInfo *exception); /* Read the contents of a file into memory. */ extern MagickExport void *FileToBlob(const char *filename, size_t *length, ExceptionInfo *exception); /* * * Junk yet to be categorized. * */ /* Reserve space for a specified output size. */ extern MagickExport MagickPassFail BlobReserveSize(Image *image, magick_off_t size); /* Copies data from the input stream to a file. Useful in case it is necessary to perform seek operations on the input data. */ extern MagickExport MagickPassFail ImageToFile(Image *image, const char *filename, ExceptionInfo *exception); /* Search for a configuration file (".mgk" file) using appropriate rules and return as an in-memory buffer. */ extern MagickExport void *GetConfigureBlob(const char *filename, char *path, size_t *length, ExceptionInfo *exception); /* Converts a least-significant byte first buffer of integers to most-significant byte first. */ extern MagickExport void MSBOrderLong(unsigned char *buffer, const size_t length); /* Converts a least-significant byte first buffer of integers to most-significant byte first. */ extern MagickExport void MSBOrderShort(unsigned char *p, const size_t length); /* Checks if the blob of the specified image is referenced by other images. If the reference count is higher then 1 a new blob is assigned to the image. */ extern MagickExport void DisassociateBlob(Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/cdl.h ================================================ /* * Copyright (C) 2009 GraphicsMagick Group * * American Society of Cinematographers Color Decision List (ASC-CDL) * implementation. * * Original implementation by Clment Follet. */ #ifndef _MAGICK_CDL_H #define _MAGICK_CDL_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport MagickPassFail CdlImage(Image *image,const char *cdl); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_CDL_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/channel.h ================================================ /* Copyright (C) 2004 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. */ #ifndef _MAGICK_CHANNEL_H #define _MAGICK_CHANNEL_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif extern MagickExport Image *ExportImageChannel(const Image *image, const ChannelType channel, ExceptionInfo *exception); extern MagickExport unsigned int GetImageChannelDepth(const Image *image, const ChannelType channel, ExceptionInfo *exception); extern MagickExport MagickPassFail ChannelImage(Image *image,const ChannelType channel), ImportImageChannel(const Image *src_image, Image *dst_image, const ChannelType channel), ImportImageChannelsMasked(const Image *source_image, Image *update_image, const ChannelType channels), SetImageChannelDepth(Image *image, const ChannelType channel, const unsigned int depth); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_CHANNEL_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/color.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Color Utility Methods. */ #ifndef _MAGICK_COLOR_H #define _MAGICK_COLOR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* PixelPacket with usage count, used to support color histograms. */ typedef struct _HistogramColorPacket { PixelPacket pixel; unsigned long count; } HistogramColorPacket; extern MagickExport HistogramColorPacket *GetColorHistogram(const Image *image,unsigned long *colors, ExceptionInfo *exception); extern MagickExport unsigned long GetNumberColors(const Image *image,FILE *file,ExceptionInfo *exception); extern MagickExport void GetColorTuple(const PixelPacket *color,const unsigned int depth, const unsigned int matte,const unsigned int hex,char *tuple); extern MagickExport MagickBool IsPaletteImage(const Image *image,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) # include "magick/color-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_COLOR_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/color_lookup.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Color Lookup Methods. */ #ifndef _MAGICK_COLOR_LOOKUP_H #define _MAGICK_COLOR_LOOKUP_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Specifications that color is compliant with. */ typedef enum { UndefinedCompliance = 0x0000, NoCompliance = 0x0000, SVGCompliance = 0x0001, X11Compliance = 0x0002, XPMCompliance = 0x0004, AllCompliance = 0xffff } ComplianceType; extern MagickExport char **GetColorList(const char *pattern,unsigned long *number_colors); extern MagickExport unsigned int QueryColorDatabase(const char *name,PixelPacket *color,ExceptionInfo *exception), QueryColorname(const Image *image,const PixelPacket *color, const ComplianceType compliance,char *name,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) # include "magick/color_lookup-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_COLOR_LOOKUP_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/colormap.h ================================================ /* Copyright (C) 2003 - 2019 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Colormap Methods */ #ifndef _MAGICK_COLORMAP_H #define _MAGICK_COLORMAP_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" extern MagickExport MagickPassFail AllocateImageColormap(Image *,const unsigned long colors), CycleColormapImage(Image *image,const int amount), ReallocateImageColormap(Image *,const unsigned int colors), ReplaceImageColormap(Image *image,const PixelPacket *colormap, const unsigned int colors), SortColormapByIntensity(Image *image); #if defined(MAGICK_IMPLEMENTATION) # include "magick/colormap-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_COLORMAP_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/colorspace.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Colorspace Methods. */ #ifndef _MAGICK_COLORSPACE_H #define _MAGICK_COLORSPACE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (QuantumDepth == 8) || (QuantumDepth == 16) /* intensity=0.299*red+0.587*green+0.114*blue. Premultiply by 1024 to obtain integral values, and then divide result by 1024 by shifting to the right by 10 bits. */ #define PixelIntensityRec601(pixel) \ ((unsigned int) \ (((unsigned int) (pixel)->red*306U+ \ (unsigned int) (pixel)->green*601U+ \ (unsigned int) (pixel)->blue*117U) \ >> 10U)) #elif (QuantumDepth == 32) /* intensity=0.299*red+0.587*green+0.114*blue. */ #define PixelIntensityRec601(pixel) \ ((unsigned int) \ (((double)306.0*(pixel)->red+ \ (double)601.0*(pixel)->green+ \ (double)117.0*(pixel)->blue) \ / 1024.0)) #endif /* intensity=0.2126*red+0.7152*green+0.0722*blue */ #define PixelIntensityRec709(pixel) \ ((unsigned int) \ (0.2126*(pixel)->red+ \ 0.7152*(pixel)->green+ \ 0.0722*(pixel)->blue)) #define PixelIntensity(pixel) PixelIntensityRec601(pixel) #define PixelIntensityToDouble(pixel) ((double)PixelIntensity(pixel)) #define PixelIntensityToQuantum(pixel) ((Quantum)PixelIntensity(pixel)) #define IsCMYKColorspace(colorspace) \ ( \ (colorspace == CMYKColorspace) \ ) #define IsGrayColorspace(colorspace) \ ( \ (colorspace == GRAYColorspace) || \ (colorspace == Rec601LumaColorspace) || \ (colorspace == Rec709LumaColorspace) \ ) #define IsRGBColorspace(colorspace) \ ( \ (IsGrayColorspace(colorspace)) || \ (colorspace == RGBColorspace) || \ (colorspace == TransparentColorspace) \ ) #define IsLABColorspace(colorspace) \ ( \ (colorspace == LABColorspace) \ ) #define IsRGBCompatibleColorspace(colorspace) \ ( \ (IsRGBColorspace(colorspace)) || \ (colorspace == CineonLogRGBColorspace ) \ ) #define IsYCbCrColorspace(colorspace) \ ( \ (colorspace == YCbCrColorspace) || \ (colorspace == Rec601YCbCrColorspace) || \ (colorspace == Rec709YCbCrColorspace) \ ) #define YCbCrColorspace Rec601YCbCrColorspace typedef enum { UndefinedColorspace, RGBColorspace, /* Plain old RGB colorspace */ GRAYColorspace, /* Plain old full-range grayscale */ TransparentColorspace, /* RGB but preserve matte channel during quantize */ OHTAColorspace, XYZColorspace, /* CIE XYZ */ YCCColorspace, /* Kodak PhotoCD PhotoYCC */ YIQColorspace, YPbPrColorspace, YUVColorspace, CMYKColorspace, /* Cyan, magenta, yellow, black, alpha */ sRGBColorspace, /* Kodak PhotoCD sRGB */ HSLColorspace, /* Hue, saturation, luminosity */ HWBColorspace, /* Hue, whiteness, blackness */ LABColorspace, /* LAB colorspace not supported yet other than via lcms */ CineonLogRGBColorspace,/* RGB data with Cineon Log scaling, 2.048 density range */ Rec601LumaColorspace, /* Luma (Y) according to ITU-R 601 */ Rec601YCbCrColorspace, /* YCbCr according to ITU-R 601 */ Rec709LumaColorspace, /* Luma (Y) according to ITU-R 709 */ Rec709YCbCrColorspace /* YCbCr according to ITU-R 709 */ } ColorspaceType; extern MagickExport MagickPassFail RGBTransformImage(ImagePtr,const ColorspaceType), TransformColorspace(ImagePtr,const ColorspaceType), TransformRGBImage(ImagePtr,const ColorspaceType); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_COLORSPACE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/command.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Image Command Methods. */ #ifndef _MAGICK_COMMAND_H #define _MAGICK_COMMAND_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif extern MagickExport MagickPassFail AnimateImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), BenchmarkImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), CompareImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), CompositeImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), ConjureImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), ConvertImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), DisplayImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), IdentifyImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), ImportImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), MagickCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), MogrifyImage(const ImageInfo *,int,char **,Image **), MogrifyImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), MogrifyImages(const ImageInfo *,int,char **,Image **), MontageImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), TimeImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception); extern MagickExport int GMCommand(int argc,char **argv); #if defined(MAGICK_IMPLEMENTATION) # include "magick/command-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/common.h ================================================ /* Copyright (C) 2009-2016 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Magick API common definitions support. */ #ifndef _MAGICK_COMMON_H #define _MAGICK_COMMON_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* * Borland C++ Builder DLL compilation defines */ #if defined(__BORLANDC__) && defined(_DLL) # pragma message("BCBMagick lib DLL export interface") # define _MAGICKDLL_ # define _MAGICKLIB_ # undef BuildMagickModules # define SupportMagickModules #endif #if defined(MSWINDOWS) && !defined(__CYGWIN__) # if defined(_MT) && defined(_DLL) && !defined(_MAGICKDLL_) && !defined(_LIB) # define _MAGICKDLL_ # endif # if defined(_MAGICKDLL_) # if defined(_VISUALC_) # pragma warning( disable: 4273 ) /* Disable the dll linkage warnings */ # endif # if !defined(_MAGICKLIB_) # define MagickExport __declspec(dllimport) # if defined(_VISUALC_) # pragma message( "Magick lib DLL import interface" ) # endif # else # define MagickExport __declspec(dllexport) # if defined(_VISUALC_) # pragma message( "Magick lib DLL export interface" ) # endif # endif # else # define MagickExport # if defined(_VISUALC_) # pragma message( "Magick lib static interface" ) # endif # endif # if defined(_DLL) && !defined(_LIB) # define ModuleExport __declspec(dllexport) # if defined(_VISUALC_) # pragma message( "Magick module DLL export interface" ) # endif # else # define ModuleExport # if defined(_VISUALC_) # pragma message( "Magick module static interface" ) # endif # endif # define MagickGlobal __declspec(thread) # if defined(_VISUALC_) # pragma warning(disable : 4018) # pragma warning(disable : 4244) # pragma warning(disable : 4244) # pragma warning(disable : 4275) /* non dll-interface class 'foo' used as base for dll-interface class 'bar' */ # pragma warning(disable : 4800) # pragma warning(disable : 4786) # pragma warning(disable : 4996) /* function deprecation warnings */ # endif #else # define MagickExport # define ModuleExport # define MagickGlobal #endif /* This size is the default minimum string allocation size (heap or stack) for a C string in GraphicsMagick. The weird size is claimed to be based on 2*FILENAME_MAX (not including terminating NULL) on some antique system. Linux has a FILENAME_MAX definition, but it is 4096 bytes. Many OSs have path limits of 1024 bytes. The FormatString() function assumes that the buffer it is writing to has at least this many bytes remaining. */ #if !defined(MaxTextExtent) # define MaxTextExtent 2053 #endif #define MagickSignature 0xabacadabUL #define MagickPassFail unsigned int #define MagickPass 1 #define MagickFail 0 #define MagickBool unsigned int #define MagickTrue 1 #define MagickFalse 0 /* Support for __attribute__ was added in GCC 2.0. It is not supported in strict ANSI mode which is indicated by __STRICT_ANSI__ being defined. http://www.ohse.de/uwe/articles/gcc-attributes.html Note that GCC 3.2 on MinGW does not define __GNUC__ or __GNUC_MINOR__. Clang/llvm and GCC 5.0 support __has_attribute(attribute) to test if an attribute is supported. Clang/llvm supports __has_builtin(builtin) to test if a builtin is supported. Clang/llvm attempts to support most GCC features. __SANITIZE_ADDRESS__ is defined by GCC and Clang if -fsanitize=address is supplied. After incuding valgrind/memcheck.h or valgrind/valgrind.h, the macro RUNNING_ON_VALGRIND can be used to test if the program is run under valgrind. See http://valgrind.org/docs/manual/manual-core-adv.html. */ #if !defined(MAGICK_ATTRIBUTE) # if ((!defined(__clang__)) && (!defined(__GNUC__) || (__GNUC__ < 2 || __STRICT_ANSI__))) # define MAGICK_ATTRIBUTE(x) /*nothing*/ # else # define MAGICK_ATTRIBUTE(x) __attribute__(x) # if ((defined(__clang__) || (defined(__GNUC__) && __GNUC__ >= 5)) && !defined(__COVERITY__)) # define MAGICK_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) # else # define MAGICK_HAS_ATTRIBUTE(attribute) (0) # endif # if (defined(__clang__) && !defined(__COVERITY__)) # define MAGICK_CLANG_HAS_BUILTIN(builtin) __has_builtin(builtin) # else # define MAGICK_CLANG_HAS_BUILTIN(builtin) (0) # endif # if ((MAGICK_HAS_ATTRIBUTE(__deprecated__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))) /* 3.1+ */ # define MAGICK_FUNC_DEPRECATED MAGICK_ATTRIBUTE((__deprecated__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__malloc__)) || \ (__GNUC__ >= 3)) /* 3.0+ */ # define MAGICK_FUNC_MALLOC MAGICK_ATTRIBUTE((__malloc__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__nonnull__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)))) /* 3.3+ */ /* Supports argument syntax like MAGICK_ATTRIBUTE((nonnull (1, 2))) but don't know how to support non-GCC fallback. */ # define MAGICK_FUNC_NONNULL MAGICK_ATTRIBUTE((__nonnull__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__noreturn__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 5)))) /* 2.5+ */ # define MAGICK_FUNC_NORETURN MAGICK_ATTRIBUTE((__noreturn__)) # endif /* clang 3.0 seems to have difficulties with __has_attribute(__const__) but clang 3.3 does not. Just assume that it is supported for clang since Linux headers are riddled with it. */ # if (defined(__clang__) || \ (((__GNUC__) > 3) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 5)))) /* 2.5+ */ # define MAGICK_FUNC_CONST MAGICK_ATTRIBUTE((__const__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__pure__)) || \ ((__GNUC__) >= 3)) /* 2.96+ */ # define MAGICK_FUNC_PURE MAGICK_ATTRIBUTE((__pure__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__unused__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 7)))) /* 2.7+ */ # define MAGICK_FUNC_UNUSED MAGICK_ATTRIBUTE((__unused__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__warn_unused_result__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)))) /* 3.3+ */ # define MAGICK_FUNC_WARN_UNUSED_RESULT MAGICK_ATTRIBUTE((__warn_unused_result__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__noinline__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))) /* 3.4+ */ # define MAGICK_FUNC_NOINLINE MAGICK_ATTRIBUTE((__noinline__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__always_inline__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))) /* 3.4+ */ # define MAGICK_FUNC_ALWAYSINLINE MAGICK_ATTRIBUTE((__always_inline__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__alloc_size__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) /* 4.3+ */ # define MAGICK_FUNC_ALLOC_SIZE_1ARG(arg_num) MAGICK_ATTRIBUTE((__alloc_size__(arg_num))) # define MAGICK_FUNC_ALLOC_SIZE_2ARG(arg_num1,arg_num2) MAGICK_ATTRIBUTE((__alloc_size__(arg_num1,arg_num2))) # endif # if ((MAGICK_HAS_ATTRIBUTE(__hot__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) /* 4.3+ */ # define MAGICK_FUNC_HOT MAGICK_ATTRIBUTE((__hot__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__cold__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) /* 4.3+ */ # define MAGICK_FUNC_COLD MAGICK_ATTRIBUTE((__cold__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__optimize__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) /* 4.3+ */ # define MAGICK_OPTIMIZE_FUNC(opt) MAGICK_ATTRIBUTE((__optimize__ (opt))) # endif /* GCC 7 and later support a fallthrough attribute to mark switch statement cases which are intended to fall through. Clang 3.5.0 supports a clang::fallthrough statement attribute while Clang 10 supports the same attribute as GCC 7. Some compilers support a FALLTHROUGH (or FALLTHRU) pre-processor comment. C++ 17 supports a standard fallthrough attribute of the form "[[fallthrough]]". See https://developers.redhat.com/blog/2017/03/10/wimplicit-fallthrough-in-gcc-7/, https://gcc.gnu.org/onlinedocs/gcc/Statement-Attributes.html, https://clang.llvm.org/docs/AttributeReference.html#fallthrough, and https://releases.llvm.org/3.7.0/tools/clang/docs/AttributeReference.html#fallthrough-clang-fallthrough Usage is to put "MAGICK_FALLTHROUGH;" where a "break;" would go. */ # if ((MAGICK_HAS_ATTRIBUTE(__fallthrough__)) || \ ((__GNUC__) >= 7)) /* 7+ */ # define MAGICK_FALLTHROUGH MAGICK_ATTRIBUTE((__fallthrough__)) # endif /* https://code.google.com/p/address-sanitizer/wiki/AddressSanitizer#Introduction To ignore certain functions, one can use the no_sanitize_address attribute supported by Clang (3.3+) and GCC (4.8+). */ # if ((MAGICK_HAS_ATTRIBUTE(__no_sanitize_address__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 8) && (__GNUC_MINOR__ >= 0)))) /* 4.8+ */ # define MAGICK_NO_SANITIZE_ADDRESS MAGICK_ATTRIBUTE((__no_sanitize_address__)) # endif # if ((MAGICK_CLANG_HAS_BUILTIN(__builtin_assume_aligned)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)))) /* 4.7+ */ # define MAGICK_ASSUME_ALIGNED(exp,align) __builtin_assume_aligned(exp,align) # endif # if ((MAGICK_CLANG_HAS_BUILTIN(__builtin_assume_aligned)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)))) /* 4.7+ */ # define MAGICK_ASSUME_ALIGNED_OFFSET(exp,align,offset) __builtin_assume_aligned(exp,align,offset) # endif # endif #endif #if !defined(MAGICK_FUNC_DEPRECATED) # define MAGICK_FUNC_DEPRECATED /*nothing*/ #endif #if !defined(MAGICK_FUNC_MALLOC) # define MAGICK_FUNC_MALLOC /*nothing*/ #endif #if !defined (MAGICK_FUNC_NONNULL) # define MAGICK_FUNC_NONNULL /*nothing*/ #endif #if !defined (MAGICK_FUNC_NORETURN) # define MAGICK_FUNC_NORETURN /*nothing*/ #endif #if !defined (MAGICK_FUNC_CONST) # define MAGICK_FUNC_CONST /*nothing*/ #endif #if !defined (MAGICK_FUNC_PURE) # define MAGICK_FUNC_PURE /*nothing*/ #endif #if !defined (MAGICK_FUNC_UNUSED) # define MAGICK_FUNC_UNUSED /*nothing*/ #endif #if !defined(MAGICK_FUNC_WARN_UNUSED_RESULT) # define MAGICK_FUNC_WARN_UNUSED_RESULT /*nothing*/ #endif #if !defined(MAGICK_FUNC_NOINLINE) # define MAGICK_FUNC_NOINLINE /*nothing*/ #endif #if !defined(MAGICK_FUNC_ALWAYSINLINE) # define MAGICK_FUNC_ALWAYSINLINE /*nothing*/ #endif #if !defined(MAGICK_FUNC_ALLOC_SIZE_1ARG) # define MAGICK_FUNC_ALLOC_SIZE_1ARG(arg_num) /*nothing*/ #endif #if !defined(MAGICK_FUNC_ALLOC_SIZE_2ARG) # define MAGICK_FUNC_ALLOC_SIZE_2ARG(arg_num1,arg_num2) /*nothing*/ #endif #if !defined(MAGICK_FUNC_HOT) # define MAGICK_FUNC_HOT /*nothing*/ #endif #if !defined(MAGICK_FUNC_COLD) # define MAGICK_FUNC_COLD /*nothing*/ #endif #if !defined(MAGICK_OPTIMIZE_FUNC) # define MAGICK_OPTIMIZE_FUNC(opt) /*nothing*/ #endif #if !defined(MAGICK_FALLTHROUGH) # define MAGICK_FALLTHROUGH /*nothing*/ #endif #if !defined(MAGICK_ASSUME_ALIGNED) # define MAGICK_ASSUME_ALIGNED(exp,align) (exp) #endif #if !defined(MAGICK_ASSUME_ALIGNED_OFFSET) # define MAGICK_ASSUME_ALIGNED_OFFSET(exp,align,offset) (exp) #endif /* The isnan and isinf macros are defined by c99 but might not always be available. If they (or a substitute) are not available, then define them to a false value. */ #if defined(isnan) #define MAGICK_ISNAN(d) isnan(d) #else #define MAGICK_ISNAN(d) (0) #endif #if defined(isinf) #define MAGICK_ISINF(d) isinf(d) #else #define MAGICK_ISINF(d) (0) #endif #if defined(isnormal) #define MAGICK_ISNORMAL(d) isnormal(d) #else #define MAGICK_ISNORMAL(d) (1) #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_COMMON_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/compare.h ================================================ /* Copyright (C) 2008 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Comparison Methods. */ #ifndef _MAGICK_COMPARE_H #define _MAGICK_COMPARE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Pixel differencing algorithms. */ typedef enum { UndefinedHighlightStyle, AssignHighlightStyle, ThresholdHighlightStyle, TintHighlightStyle, XorHighlightStyle } HighlightStyle; typedef struct _DifferenceImageOptions { ChannelType channel; /* Channel(s) to difference */ HighlightStyle highlight_style; /* Pixel annotation style */ PixelPacket highlight_color; /* Changed pixel highlight color */ } DifferenceImageOptions; extern MagickExport void InitializeDifferenceImageOptions(DifferenceImageOptions *options, ExceptionInfo *exception); extern MagickExport Image *DifferenceImage(const Image *reference_image,const Image *compare_image, const DifferenceImageOptions *difference_options, ExceptionInfo *exception); /* Pixel error metrics. */ typedef enum { UndefinedMetric, MeanAbsoluteErrorMetric, MeanSquaredErrorMetric, PeakAbsoluteErrorMetric, PeakSignalToNoiseRatioMetric, RootMeanSquaredErrorMetric } MetricType; /* Pixel difference statistics. */ typedef struct _DifferenceStatistics { double red, green, blue, opacity, combined; } DifferenceStatistics; extern MagickExport void InitializeDifferenceStatistics(DifferenceStatistics *difference_statistics, ExceptionInfo *exception); extern MagickExport MagickPassFail GetImageChannelDifference(const Image *reference_image, const Image *compare_image, const MetricType metric, DifferenceStatistics *statistics, ExceptionInfo *exception), GetImageChannelDistortion(const Image *reference_image, const Image *compare_image, const ChannelType channel, const MetricType metric, double *distortion, ExceptionInfo *exception), GetImageDistortion(const Image *reference_image, const Image *compare_image, const MetricType metric, double *distortion, ExceptionInfo *exception); extern MagickExport MagickBool IsImagesEqual(Image *,const Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_COMPARE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/composite.h ================================================ /* Copyright (C) 2003 - 2010 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Composite Methods. */ #ifndef _MAGICK_COMPOSITE_H #define _MAGICK_COMPOSITE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Special options required by some composition operators. */ typedef struct _CompositeOptions_t { /* ModulateComposite */ double percent_brightness; /* ThresholdComposite */ double amount; double threshold; } CompositeOptions_t; extern MagickExport MagickPassFail CompositeImage(Image *canvas_image,const CompositeOperator compose, const Image *update_image, const long x_offset,const long y_offset), CompositeImageRegion(const CompositeOperator compose, const CompositeOptions_t *options, const unsigned long columns, const unsigned long rows, const Image *update_image, const long update_x, const long update_y, Image *canvas_image, const long canvas_x, const long canvas_y, ExceptionInfo *exception), MagickCompositeImageUnderColor(Image *image,const PixelPacket *undercolor, ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_COMPOSITE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/compress.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Image Compression/Decompression Methods. */ #ifndef _MAGICK_COMPRESS_H #define _MAGICK_COMPRESS_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Typedef declaration. */ typedef struct _Ascii85Info { long offset, line_break; magick_uint8_t buffer[10]; } Ascii85Info; /* TODO: Clean up the interface between BLOB write functions, compression functions, and encoding functions so they may be hooked into/stacked on top of each other. Most are (or can be changed to be) stream based. */ typedef unsigned int (*WriteByteHook)(Image *, const magick_uint8_t, void *info); /* Commonly used byte writer hooks. */ extern MagickExport unsigned int Ascii85WriteByteHook(Image *image, const magick_uint8_t code, void *info), BlobWriteByteHook(Image *image, const magick_uint8_t code, void *info); /* Compress methods. */ extern MagickExport MagickPassFail HuffmanDecodeImage(Image *image), HuffmanEncodeImage(const ImageInfo *image_info,Image *image), HuffmanEncode2Image(const ImageInfo *image_info,Image *image,WriteByteHook write_byte,void *info), LZWEncodeImage(Image *image,const size_t length,magick_uint8_t *pixels), LZWEncode2Image(Image *image,const size_t length,magick_uint8_t *pixels,WriteByteHook write_byte,void *info), PackbitsEncodeImage(Image *image,const size_t length,magick_uint8_t *pixels), PackbitsEncode2Image(Image *image,const size_t length,magick_uint8_t *pixels,WriteByteHook write_byte,void *info); extern MagickExport unsigned char *ImageToHuffman2DBlob(const Image *image,const ImageInfo *image_info, size_t *length,ExceptionInfo *exception), *ImageToJPEGBlob(const Image *image,const ImageInfo *image_info, size_t *length,ExceptionInfo *exception); extern MagickExport void Ascii85Encode(Image *image,const magick_uint8_t code), Ascii85Flush(Image *image), Ascii85Initialize(Image *image); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/confirm_access.h ================================================ /* Copyright (C) 2009 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Access Confirmation Methods. */ #ifndef _MAGICK_CONFIRM_ACCESS_H #define _MAGICK_CONFIRM_ACCESS_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif typedef enum { UndefinedConfirmAccessMode, FileExecuteConfirmAccessMode, /* Path is to be opened for execution */ FileReadConfirmAccessMode, /* Path is to be opened for read */ FileWriteConfirmAccessMode, /* Path is to be opened for write */ URLGetFTPConfirmAccessMode, /* ftp:// URL get */ URLGetFileConfirmAccessMode, /* file:// URL get */ URLGetHTTPConfirmAccessMode /* http:// URL get */ } ConfirmAccessMode; typedef MagickPassFail (*ConfirmAccessHandler)(const ConfirmAccessMode mode, const char *path, ExceptionInfo *exception); extern MagickExport MagickPassFail MagickConfirmAccess(const ConfirmAccessMode mode, const char *path, ExceptionInfo *exception); extern MagickExport ConfirmAccessHandler MagickSetConfirmAccessHandler(ConfirmAccessHandler handler); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_CONFIRM_ACCESS_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/constitute.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Constitute Methods. */ #ifndef _MAGICK_CONSTITUTE_H #define _MAGICK_CONSTITUTE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Quantum import/export types as used by ImportImagePixelArea() and ExportImagePixelArea(). Values are imported or exported in network byte order ("big endian") by default, but little endian may be selected via the 'endian' option in ExportPixelAreaOptions and ImportPixelAreaOptions. */ typedef enum { UndefinedQuantum, /* Not specified */ IndexQuantum, /* Colormap indexes */ GrayQuantum, /* Grayscale values (minimum value is black) */ IndexAlphaQuantum, /* Colormap indexes with transparency */ GrayAlphaQuantum, /* Grayscale values with transparency */ RedQuantum, /* Red values only (RGBA) */ CyanQuantum, /* Cyan values only (CMYKA) */ GreenQuantum, /* Green values only (RGBA) */ YellowQuantum, /* Yellow values only (CMYKA) */ BlueQuantum, /* Blue values only (RGBA) */ MagentaQuantum, /* Magenta values only (CMYKA) */ AlphaQuantum, /* Transparency values (RGBA or CMYKA) */ BlackQuantum, /* Black values only (CMYKA) */ RGBQuantum, /* Red, green, and blue values */ RGBAQuantum, /* Red, green, blue, and transparency values */ CMYKQuantum, /* Cyan, magenta, yellow, and black values */ CMYKAQuantum, /* Cyan, magenta, yellow, black, and transparency values */ CIEYQuantum, /* CIE Y values, based on CCIR-709 primaries */ CIEXYZQuantum /* CIE XYZ values, based on CCIR-709 primaries */ } QuantumType; /* Quantum sample type for when exporting/importing a pixel area. */ typedef enum { UndefinedQuantumSampleType, /* Not specified */ UnsignedQuantumSampleType, /* Unsigned integral type (1-32 or 64 bits) */ FloatQuantumSampleType /* Floating point type (16, 24, 32, or 64 bit) */ } QuantumSampleType; /* Quantum size types as used by ConstituteImage() and DispatchImage()/ */ typedef enum { CharPixel, /* Unsigned 8 bit 'unsigned char' */ ShortPixel, /* Unsigned 16 bit 'unsigned short int' */ IntegerPixel, /* Unsigned 32 bit 'unsigned int' */ LongPixel, /* Unsigned 32 or 64 bit (CPU dependent) 'unsigned long' */ FloatPixel, /* Floating point 32-bit 'float' */ DoublePixel /* Floating point 64-bit 'double' */ } StorageType; /* Additional options for ExportImagePixelArea() */ typedef struct _ExportPixelAreaOptions { QuantumSampleType sample_type; /* Quantum sample type */ double double_minvalue, /* Minimum value (default 0.0) for linear floating point samples */ double_maxvalue; /* Maximum value (default 1.0) for linear floating point samples */ MagickBool grayscale_miniswhite; /* Grayscale minimum value is white rather than black */ unsigned long pad_bytes; /* Number of pad bytes to output after pixel data */ unsigned char pad_value; /* Value to use when padding end of pixel data */ EndianType endian; /* Endian orientation for 16/32/64 bit types (default MSBEndian) */ unsigned long signature; } ExportPixelAreaOptions; /* Optional results info for ExportImagePixelArea() */ typedef struct _ExportPixelAreaInfo { size_t bytes_exported; /* Number of bytes which were exported */ } ExportPixelAreaInfo; /* Additional options for ImportImagePixelArea() */ typedef struct _ImportPixelAreaOptions { QuantumSampleType sample_type; /* Quantum sample type */ double double_minvalue, /* Minimum value (default 0.0) for linear floating point samples */ double_maxvalue; /* Maximum value (default 1.0) for linear floating point samples */ MagickBool grayscale_miniswhite; /* Grayscale minimum value is white rather than black */ EndianType endian; /* Endian orientation for 16/32/64 bit types (default MSBEndian) */ unsigned long signature; } ImportPixelAreaOptions; /* Optional results info for ImportImagePixelArea() */ typedef struct _ImportPixelAreaInfo { size_t bytes_imported; /* Number of bytes which were imported */ } ImportPixelAreaInfo; extern MagickExport const char *StorageTypeToString(const StorageType storage_type), *QuantumSampleTypeToString(const QuantumSampleType sample_type), *QuantumTypeToString(const QuantumType quantum_type); extern MagickExport Image *ConstituteImage(const unsigned long width,const unsigned long height, const char *map,const StorageType type,const void *pixels, ExceptionInfo *exception), *ConstituteTextureImage(const unsigned long columns,const unsigned long rows, const Image *texture,ExceptionInfo *exception), *PingImage(const ImageInfo *image_info,ExceptionInfo *exception), *ReadImage(const ImageInfo *image_info,ExceptionInfo *exception), *ReadInlineImage(const ImageInfo *image_info,const char *content, ExceptionInfo *exception); extern MagickExport MagickPassFail DispatchImage(const Image *image,const long x_offset,const long y_offset, const unsigned long columns,const unsigned long rows,const char *map, const StorageType type,void *pixels,ExceptionInfo *exception), ExportImagePixelArea(const Image *image,const QuantumType quantum_type, const unsigned int quantum_size,unsigned char *destination, const ExportPixelAreaOptions *options,ExportPixelAreaInfo *export_info), ExportViewPixelArea(const ViewInfo *view,const QuantumType quantum_type, const unsigned int quantum_size,unsigned char *destination, const ExportPixelAreaOptions *options,ExportPixelAreaInfo *export_info); extern MagickExport MagickPassFail ImportImagePixelArea(Image *image,const QuantumType quantum_type, const unsigned int quantum_size,const unsigned char *source, const ImportPixelAreaOptions *options,ImportPixelAreaInfo *import_info), ImportViewPixelArea(ViewInfo *view,const QuantumType quantum_type, const unsigned int quantum_size,const unsigned char *source, const ImportPixelAreaOptions *options,ImportPixelAreaInfo *import_info), WriteImage(const ImageInfo *image_info,Image *image), WriteImages(const ImageInfo *image_info,Image *image,const char *filename, ExceptionInfo *exception), WriteImagesFile(const ImageInfo *image_info,Image *image,FILE * file, ExceptionInfo *exception); extern MagickExport void ExportPixelAreaOptionsInit(ExportPixelAreaOptions *options), ImportPixelAreaOptionsInit(ImportPixelAreaOptions *options); extern MagickExport MagickPassFail MagickFindRawImageMinMax(Image *image, EndianType endian, unsigned long width, unsigned long height,StorageType type, unsigned scanline_octets, void *scanline_buffer, double *min, double *max); extern MagickExport unsigned int MagickGetQuantumSamplesPerPixel(const QuantumType quantum_type) MAGICK_FUNC_CONST; #if defined(MAGICK_IMPLEMENTATION) # include "magick/constitute-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_CONSTITUTE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/decorate.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Decorate Methods. */ #ifndef _MAGICK_DECORATE_H #define _MAGICK_DECORATE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *BorderImage(const Image *,const RectangleInfo *,ExceptionInfo *), *FrameImage(const Image *,const FrameInfo *,ExceptionInfo *); MagickExport unsigned int RaiseImage(Image *,const RectangleInfo *,const int); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_DECORATE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/delegate.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Methods to Read/Write/Invoke Delegates. */ #ifndef _MAGICK_DELEGATE_H #define _MAGICK_DELEGATE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Delegate structure definitions. */ typedef struct _DelegateInfo { char *path, /* Path to delegate configuation file */ *decode, /* Decode from format */ *encode; /* Transcode to format */ char *commands; /* Commands to execute */ int mode; /* <0 = encoder, >0 = decoder */ MagickBool stealth; /* Don't list this delegate */ unsigned long signature; struct _DelegateInfo *previous, *next; } DelegateInfo; /* Magick delegate methods. */ extern MagickExport char *GetDelegateCommand(const ImageInfo *image_info,Image *image, const char *decode,const char *encode, ExceptionInfo *exception); extern MagickExport const DelegateInfo *GetDelegateInfo(const char *decode,const char *encode, ExceptionInfo *exception), *GetPostscriptDelegateInfo(const ImageInfo *image_info, unsigned int *antialias, ExceptionInfo *exception); extern MagickExport DelegateInfo *SetDelegateInfo(DelegateInfo *); extern MagickExport MagickPassFail InvokePostscriptDelegate(const unsigned int verbose,const char *command, ExceptionInfo *exception), InvokeDelegate(ImageInfo *image_info,Image *image,const char *decode, const char *encode,ExceptionInfo *exception), ListDelegateInfo(FILE *file,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) #if defined(HasGS) #include "ghostscript/iapi.h" #endif #ifndef gs_main_instance_DEFINED # define gs_main_instance_DEFINED typedef struct gs_main_instance_s gs_main_instance; #endif #if !defined(MagickDLLCall) # if defined(MSWINDOWS) # define MagickDLLCall __stdcall # else # define MagickDLLCall # endif #endif /* Define a vector of Ghostscript library callback functions so that DLL/shared and static Ghostscript libbraries may be handled identically. These definitions must be compatible with those in the Ghostscript API headers (which we don't require). http://pages.cs.wisc.edu/~ghost/doc/cvs/API.htm */ typedef struct _GhostscriptVectors { /* Exit the interpreter (gsapi_exit)*/ int (MagickDLLCall *exit)(gs_main_instance *instance); /* Destroy instance of Ghostscript. Call exit first! (gsapi_delete_instance) */ void (MagickDLLCall *delete_instance)(gs_main_instance *instance); /* Initialize the Ghostscript interpreter (gsapi_init_with_args) */ int (MagickDLLCall *init_with_args)(gs_main_instance *instance,int argc, char **argv); /* Create a new instance of the Ghostscript interpreter (gsapi_new_instance) */ int (MagickDLLCall *new_instance)(gs_main_instance **pinstance, void *caller_handle); /* Execute string command in Ghostscript interpreter (gsapi_run_string) */ int (MagickDLLCall *run_string)(gs_main_instance *instance,const char *str, int user_errors,int *pexit_code); } GhostscriptVectors; extern MagickExport void DestroyDelegateInfo(void); extern MagickPassFail InitializeDelegateInfo(void); #endif /* MAGICK_IMPLEMENTATION */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_DELEGATE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/deprecate.h ================================================ /* Copyright (C) 2003, 2008 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Log methods. */ #ifndef _MAGICK_DEPRECATE_H #define _MAGICK_DEPRECATE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Legacy names for (possibly) large integral types */ #if !defined(ExtendedSignedIntegralType) # define ExtendedSignedIntegralType magick_int64_t #endif #if !defined(ExtendedUnsignedIntegralType) # define ExtendedUnsignedIntegralType magick_uint64_t #endif /* Compatibility definitions to handle the renaming of ExtendedSignedIntegralType and ExtendedUnsignedIntegralType to MagickSignedType and MagickUnsignedType which occured in ImageMagick 5.5.8. ImageMagick 5.5.8 also introduced MagickRationalType. */ #if !defined(MagickSignedType) # define MagickSignedType magick_int64_t #endif #if !defined(MagickUnsignedType) # define MagickUnsignedType magick_uint64_t #endif #if !defined(MagickRationalType) # if defined(HAVE_LONG_DOUBLE) # define MagickRationalType long double # else # define MagickRationalType double # endif #endif extern MagickExport unsigned int PopImagePixels(const Image *,const QuantumType,unsigned char *) MAGICK_FUNC_DEPRECATED; extern MagickExport unsigned int PushImagePixels(Image *,const QuantumType,const unsigned char *) MAGICK_FUNC_DEPRECATED; extern MagickExport void *AcquireMemory(const size_t) MAGICK_FUNC_DEPRECATED MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(1); extern MagickExport void *CloneMemory(void *,const void *,const size_t) MAGICK_FUNC_DEPRECATED; extern MagickExport void LiberateMemory(void **) MAGICK_FUNC_DEPRECATED; extern MagickExport void ReacquireMemory(void **,const size_t) MAGICK_FUNC_DEPRECATED; extern MagickExport const PixelPacket *AcquireCacheView(ViewInfo *view, const long x,const long y,const unsigned long columns, const unsigned long rows,ExceptionInfo *exception) MAGICK_FUNC_DEPRECATED; extern MagickExport PixelPacket *GetCacheView(ViewInfo *view,const long x,const long y, const unsigned long columns,const unsigned long rows) MAGICK_FUNC_DEPRECATED; extern MagickExport PixelPacket *SetCacheView(ViewInfo *view,const long x,const long y, const unsigned long columns,const unsigned long rows) MAGICK_FUNC_DEPRECATED; extern MagickExport MagickPassFail SyncCacheView(ViewInfo *view) MAGICK_FUNC_DEPRECATED; #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/describe.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Describe Methods. */ #ifndef _MAGICK_DESCRIBE_H #define _MAGICK_DESCRIBE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" extern MagickExport MagickPassFail DescribeImage(Image *image,FILE *file,const MagickBool verbose); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_DESCRIBE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/draw.h ================================================ /* Copyright (C) 2003-2018 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Drawing API. Usage synopsis: DrawContext context; context = DrawAllocateContext((DrawInfo*)NULL, image); [ any number of drawing commands ] DrawSetStrokeColorString(context,"black"); DrawSetFillColorString(context,"#ff00ff"); DrawSetStrokeWidth(context,4); DrawRectangle(context,72,72,144,144); DrawRender(context); DrawDestroyContext(context); */ #ifndef _MAGICK_DRAW_H #define _MAGICK_DRAW_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/render.h" typedef struct _DrawContext *DrawContext; extern MagickExport ClipPathUnits DrawGetClipUnits(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport DrawInfo *DrawPeekGraphicContext(const DrawContext context); extern MagickExport DecorationType DrawGetTextDecoration(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport DrawContext DrawAllocateContext(const DrawInfo *draw_info, Image *image); extern MagickExport FillRule DrawGetClipRule(DrawContext context) MAGICK_FUNC_PURE, DrawGetFillRule(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport GravityType DrawGetGravity(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport LineCap DrawGetStrokeLineCap(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport LineJoin DrawGetStrokeLineJoin(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport PixelPacket DrawGetFillColor(DrawContext context) MAGICK_FUNC_PURE, DrawGetStrokeColor(DrawContext context) MAGICK_FUNC_PURE, DrawGetTextUnderColor(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport StretchType DrawGetFontStretch(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport StyleType DrawGetFontStyle(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport char *DrawGetClipPath(DrawContext context), *DrawGetFont(DrawContext context), *DrawGetFontFamily(DrawContext context), *DrawGetTextEncoding(DrawContext context); extern MagickExport int DrawRender(const DrawContext context); extern MagickExport unsigned int DrawGetStrokeAntialias(DrawContext context) MAGICK_FUNC_PURE, DrawGetTextAntialias(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport unsigned long DrawGetFontWeight(DrawContext context) MAGICK_FUNC_PURE, DrawGetStrokeMiterLimit(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport double DrawGetFillOpacity(DrawContext context) MAGICK_FUNC_PURE, DrawGetFontSize(DrawContext context) MAGICK_FUNC_PURE, *DrawGetStrokeDashArray(DrawContext context, unsigned long *num_elems), DrawGetStrokeDashOffset(DrawContext context) MAGICK_FUNC_PURE, DrawGetStrokeOpacity(DrawContext context) MAGICK_FUNC_PURE, DrawGetStrokeWidth(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport void DrawAffine(DrawContext context, const AffineMatrix *affine), DrawAnnotation(DrawContext context, const double x, const double y, const unsigned char *text), DrawArc(DrawContext context, const double sx, const double sy, const double ex, const double ey, const double sd, const double ed), DrawBezier(DrawContext context, const unsigned long num_coords, const PointInfo * coordinates), DrawCircle(DrawContext context, const double ox, const double oy, const double px, const double py), DrawColor(DrawContext context, const double x, const double y, const PaintMethod paintMethod), DrawComment(DrawContext context,const char* comment), DrawDestroyContext(DrawContext context), DrawEllipse(DrawContext context, const double ox, const double oy, const double rx, const double ry, const double start, const double end), DrawComposite(DrawContext context, const CompositeOperator composite_operator, const double x, const double y, const double width, const double height, const Image * image ), DrawLine(DrawContext context, const double sx, const double sy, const double ex, const double ey), DrawMatte(DrawContext context, const double x, const double y, const PaintMethod paint_method), DrawPathClose(DrawContext context), DrawPathCurveToAbsolute(DrawContext context, const double x1, const double y1, const double x2, const double y2, const double x, const double y), DrawPathCurveToRelative(DrawContext context, const double x1, const double y1, const double x2, const double y2, const double x, const double y), DrawPathCurveToQuadraticBezierAbsolute(DrawContext context, const double x1, const double y1, const double x, const double y), DrawPathCurveToQuadraticBezierRelative(DrawContext context, const double x1, const double y1, const double x, const double y), DrawPathCurveToQuadraticBezierSmoothAbsolute(DrawContext context, const double x, const double y), DrawPathCurveToQuadraticBezierSmoothRelative(DrawContext context, const double x, const double y), DrawPathCurveToSmoothAbsolute(DrawContext context, const double x2, const double y2, const double x, const double y), DrawPathCurveToSmoothRelative(DrawContext context, const double x2, const double y2, const double x, const double y), DrawPathEllipticArcAbsolute(DrawContext context, const double rx, const double ry, const double x_axis_rotation, unsigned int large_arc_flag, unsigned int sweep_flag, const double x, const double y), DrawPathEllipticArcRelative(DrawContext context, const double rx, const double ry, const double x_axis_rotation, unsigned int large_arc_flag, unsigned int sweep_flag, const double x, const double y), DrawPathFinish(DrawContext context), DrawPathLineToAbsolute(DrawContext context, const double x, const double y), DrawPathLineToRelative(DrawContext context, const double x, const double y), DrawPathLineToHorizontalAbsolute(DrawContext context, const double x), DrawPathLineToHorizontalRelative(DrawContext context, const double x), DrawPathLineToVerticalAbsolute(DrawContext context, const double y), DrawPathLineToVerticalRelative(DrawContext context, const double y), DrawPathMoveToAbsolute(DrawContext context, const double x, const double y), DrawPathMoveToRelative(DrawContext context, const double x, const double y), DrawPathStart(DrawContext context), DrawPoint(DrawContext context, const double x, const double y), DrawPolygon(DrawContext context, const unsigned long num_coords, const PointInfo * coordinates), DrawPolyline(DrawContext context, const unsigned long num_coords, const PointInfo * coordinates), DrawPopClipPath(DrawContext context), DrawPopDefs(DrawContext context), DrawPopGraphicContext(DrawContext context), DrawPopPattern(DrawContext context), DrawPushClipPath(DrawContext context, const char *clip_path_id), DrawPushDefs(DrawContext context), DrawPushGraphicContext(DrawContext context), DrawPushPattern(DrawContext context, const char *pattern_id, const double x, const double y, const double width, const double height), DrawRectangle(DrawContext context, const double x1, const double y1, const double x2, const double y2), DrawRoundRectangle(DrawContext context, double x1, double y1, double x2, double y2, double rx, double ry), DrawScale(DrawContext context, const double x, const double y), DrawSetClipPath(DrawContext context, const char *clip_path), DrawSetClipRule(DrawContext context, const FillRule fill_rule), DrawSetClipUnits(DrawContext context, const ClipPathUnits clip_units), DrawSetFillColor(DrawContext context, const PixelPacket *fill_color), DrawSetFillColorString(DrawContext context, const char *fill_color), DrawSetFillOpacity(DrawContext context, const double fill_opacity), DrawSetFillRule(DrawContext context, const FillRule fill_rule), DrawSetFillPatternURL(DrawContext context, const char *fill_url), DrawSetFont(DrawContext context, const char *font_name), DrawSetFontFamily(DrawContext context, const char *font_family), DrawSetFontSize(DrawContext context, const double font_pointsize), DrawSetFontStretch(DrawContext context, const StretchType font_stretch), DrawSetFontStyle(DrawContext context, const StyleType font_style), DrawSetFontWeight(DrawContext context, const unsigned long font_weight), DrawSetGravity(DrawContext context, const GravityType gravity), DrawRotate(DrawContext context, const double degrees), DrawSkewX(DrawContext context, const double degrees), DrawSkewY(DrawContext context, const double degrees), /* DrawSetStopColor(DrawContext context, const PixelPacket * color, const double offset), */ DrawSetStrokeAntialias(DrawContext context, const unsigned int true_false), DrawSetStrokeColor(DrawContext context, const PixelPacket *stroke_color), DrawSetStrokeColorString(DrawContext context, const char *stroke_color), DrawSetStrokeDashArray(DrawContext context, const unsigned long num_elems, const double *dasharray), DrawSetStrokeDashOffset(DrawContext context,const double dashoffset), DrawSetStrokeLineCap(DrawContext context, const LineCap linecap), DrawSetStrokeLineJoin(DrawContext context, const LineJoin linejoin), DrawSetStrokeMiterLimit(DrawContext context,const unsigned long miterlimit), DrawSetStrokeOpacity(DrawContext context, const double opacity), DrawSetStrokePatternURL(DrawContext context, const char* stroke_url), DrawSetStrokeWidth(DrawContext context, const double width), DrawSetTextAntialias(DrawContext context, const unsigned int true_false), DrawSetTextDecoration(DrawContext context, const DecorationType decoration), DrawSetTextEncoding(DrawContext context, const char *encoding), DrawSetTextUnderColor(DrawContext context, const PixelPacket *color), DrawSetTextUnderColorString(DrawContext context, const char *under_color), DrawSetViewbox(DrawContext context, unsigned long x1, unsigned long y1, unsigned long x2, unsigned long y2), DrawTranslate(DrawContext context, const double x, const double y); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/effect.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Effect Methods. */ #ifndef _MAGICK_EFFECT_H #define _MAGICK_EFFECT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *AdaptiveThresholdImage(const Image *,const unsigned long,const unsigned long, const double,ExceptionInfo *), *AddNoiseImage(const Image *,const NoiseType,ExceptionInfo *), *AddNoiseImageChannel(const Image *image,const ChannelType channel, const NoiseType noise_type,ExceptionInfo *exception), *BlurImage(const Image *,const double,const double,ExceptionInfo *), *BlurImageChannel(const Image *image,const ChannelType channel, const double radius,const double sigma,ExceptionInfo *exception), *ConvolveImage(const Image *,const unsigned int,const double *, ExceptionInfo *), *DespeckleImage(const Image *,ExceptionInfo *), *EdgeImage(const Image *,const double,ExceptionInfo *), *EmbossImage(const Image *,const double,const double,ExceptionInfo *), *EnhanceImage(const Image *,ExceptionInfo *), *GaussianBlurImage(const Image *,const double,const double,ExceptionInfo *), *GaussianBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception), *MedianFilterImage(const Image *,const double,ExceptionInfo *), *MotionBlurImage(const Image *,const double,const double,const double, ExceptionInfo *), *ReduceNoiseImage(const Image *,const double,ExceptionInfo *), *ShadeImage(const Image *,const unsigned int,double,double,ExceptionInfo *), *SharpenImage(const Image *,const double,const double,ExceptionInfo *), *SharpenImageChannel(const Image *image,const ChannelType channel, const double radius,const double sigma,ExceptionInfo *exception), *SpreadImage(const Image *,const unsigned int,ExceptionInfo *), *UnsharpMaskImage(const Image *,const double,const double,const double, const double,ExceptionInfo *), *UnsharpMaskImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, const double amount,const double threshold, ExceptionInfo *exception); extern MagickExport MagickPassFail BlackThresholdImage(Image *image,const char *thresholds), ChannelThresholdImage(Image *,const char *), RandomChannelThresholdImage(Image *,const char *,const char *, ExceptionInfo *exception), ThresholdImage(Image *,const double), WhiteThresholdImage(Image *image,const char *thresholds); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_EFFECT_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/enhance.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Enhancement Methods. */ #ifndef _MAGICK_ENHANCE_H #define _MAGICK_ENHANCE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport MagickPassFail ContrastImage(Image *,const unsigned int), EqualizeImage(Image *), GammaImage(Image *,const char *), LevelImage(Image *,const char *), LevelImageChannel(Image *,const ChannelType,const double,const double, const double), ModulateImage(Image *,const char *), NegateImage(Image *,const unsigned int), NormalizeImage(Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_ENHANCE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/error.h ================================================ /* Copyright (C) 2003-2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Exception Methods. */ #ifndef _MAGICK_ERROR_H #define _MAGICK_ERROR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Enum declarations. */ typedef enum { UndefinedExceptionBase = 0, ExceptionBase = 1, ResourceBase = 2, ResourceLimitBase = 2, TypeBase = 5, AnnotateBase = 5, OptionBase = 10, DelegateBase = 15, MissingDelegateBase = 20, CorruptImageBase = 25, FileOpenBase = 30, BlobBase = 35, StreamBase = 40, CacheBase = 45, CoderBase = 50, ModuleBase = 55, DrawBase = 60, RenderBase = 60, ImageBase = 65, WandBase = 67, TemporaryFileBase = 70, TransformBase = 75, XServerBase = 80, X11Base = 81, UserBase = 82, MonitorBase = 85, LocaleBase = 86, DeprecateBase = 87, RegistryBase = 90, ConfigureBase = 95 } ExceptionBaseType; typedef enum { UndefinedException = 0, EventException = 100, ExceptionEvent = EventException + ExceptionBase, ResourceEvent = EventException + ResourceBase, ResourceLimitEvent = EventException + ResourceLimitBase, TypeEvent = EventException + TypeBase, AnnotateEvent = EventException + AnnotateBase, OptionEvent = EventException + OptionBase, DelegateEvent = EventException + DelegateBase, MissingDelegateEvent = EventException + MissingDelegateBase, CorruptImageEvent = EventException + CorruptImageBase, FileOpenEvent = EventException + FileOpenBase, BlobEvent = EventException + BlobBase, StreamEvent = EventException + StreamBase, CacheEvent = EventException + CacheBase, CoderEvent = EventException + CoderBase, ModuleEvent = EventException + ModuleBase, DrawEvent = EventException + DrawBase, RenderEvent = EventException + RenderBase, ImageEvent = EventException + ImageBase, WandEvent = EventException + WandBase, TemporaryFileEvent = EventException + TemporaryFileBase, TransformEvent = EventException + TransformBase, XServerEvent = EventException + XServerBase, X11Event = EventException + X11Base, UserEvent = EventException + UserBase, MonitorEvent = EventException + MonitorBase, LocaleEvent = EventException + LocaleBase, DeprecateEvent = EventException + DeprecateBase, RegistryEvent = EventException + RegistryBase, ConfigureEvent = EventException + ConfigureBase, WarningException = 300, ExceptionWarning = WarningException + ExceptionBase, ResourceWarning = WarningException + ResourceBase, ResourceLimitWarning = WarningException + ResourceLimitBase, TypeWarning = WarningException + TypeBase, AnnotateWarning = WarningException + AnnotateBase, OptionWarning = WarningException + OptionBase, DelegateWarning = WarningException + DelegateBase, MissingDelegateWarning = WarningException + MissingDelegateBase, CorruptImageWarning = WarningException + CorruptImageBase, FileOpenWarning = WarningException + FileOpenBase, BlobWarning = WarningException + BlobBase, StreamWarning = WarningException + StreamBase, CacheWarning = WarningException + CacheBase, CoderWarning = WarningException + CoderBase, ModuleWarning = WarningException + ModuleBase, DrawWarning = WarningException + DrawBase, RenderWarning = WarningException + RenderBase, ImageWarning = WarningException + ImageBase, WandWarning = WarningException + WandBase, TemporaryFileWarning = WarningException + TemporaryFileBase, TransformWarning = WarningException + TransformBase, XServerWarning = WarningException + XServerBase, X11Warning = WarningException + X11Base, UserWarning = WarningException + UserBase, MonitorWarning = WarningException + MonitorBase, LocaleWarning = WarningException + LocaleBase, DeprecateWarning = WarningException + DeprecateBase, RegistryWarning = WarningException + RegistryBase, ConfigureWarning = WarningException + ConfigureBase, ErrorException = 400, ExceptionError = ErrorException + ExceptionBase, ResourceError = ErrorException + ResourceBase, ResourceLimitError = ErrorException + ResourceLimitBase, TypeError = ErrorException + TypeBase, AnnotateError = ErrorException + AnnotateBase, OptionError = ErrorException + OptionBase, DelegateError = ErrorException + DelegateBase, MissingDelegateError = ErrorException + MissingDelegateBase, CorruptImageError = ErrorException + CorruptImageBase, FileOpenError = ErrorException + FileOpenBase, BlobError = ErrorException + BlobBase, StreamError = ErrorException + StreamBase, CacheError = ErrorException + CacheBase, CoderError = ErrorException + CoderBase, ModuleError = ErrorException + ModuleBase, DrawError = ErrorException + DrawBase, RenderError = ErrorException + RenderBase, ImageError = ErrorException + ImageBase, WandError = ErrorException + WandBase, TemporaryFileError = ErrorException + TemporaryFileBase, TransformError = ErrorException + TransformBase, XServerError = ErrorException + XServerBase, X11Error = ErrorException + X11Base, UserError = ErrorException + UserBase, MonitorError = ErrorException + MonitorBase, LocaleError = ErrorException + LocaleBase, DeprecateError = ErrorException + DeprecateBase, RegistryError = ErrorException + RegistryBase, ConfigureError = ErrorException + ConfigureBase, FatalErrorException = 700, ExceptionFatalError = FatalErrorException + ExceptionBase, ResourceFatalError = FatalErrorException + ResourceBase, ResourceLimitFatalError = FatalErrorException + ResourceLimitBase, TypeFatalError = FatalErrorException + TypeBase, AnnotateFatalError = FatalErrorException + AnnotateBase, OptionFatalError = FatalErrorException + OptionBase, DelegateFatalError = FatalErrorException + DelegateBase, MissingDelegateFatalError = FatalErrorException + MissingDelegateBase, CorruptImageFatalError = FatalErrorException + CorruptImageBase, FileOpenFatalError = FatalErrorException + FileOpenBase, BlobFatalError = FatalErrorException + BlobBase, StreamFatalError = FatalErrorException + StreamBase, CacheFatalError = FatalErrorException + CacheBase, CoderFatalError = FatalErrorException + CoderBase, ModuleFatalError = FatalErrorException + ModuleBase, DrawFatalError = FatalErrorException + DrawBase, RenderFatalError = FatalErrorException + RenderBase, ImageFatalError = FatalErrorException + ImageBase, WandFatalError = FatalErrorException + WandBase, TemporaryFileFatalError = FatalErrorException + TemporaryFileBase, TransformFatalError = FatalErrorException + TransformBase, XServerFatalError = FatalErrorException + XServerBase, X11FatalError = FatalErrorException + X11Base, UserFatalError = FatalErrorException + UserBase, MonitorFatalError = FatalErrorException + MonitorBase, LocaleFatalError = FatalErrorException + LocaleBase, DeprecateFatalError = FatalErrorException + DeprecateBase, RegistryFatalError = FatalErrorException + RegistryBase, ConfigureFatalError = FatalErrorException + ConfigureBase } ExceptionType; /* Typedef declarations. */ /* ExceptionInfo is used to report exceptions to higher level routines, and to the user. */ typedef struct _ExceptionInfo { /* Exception severity, reason, and description */ ExceptionType severity; char *reason, *description; /* Value of errno (or equivalent) when exception was thrown. */ int error_number; /* Reporting source module, function (if available), and source module line. */ char *module, *function; unsigned long line; /* Structure sanity check */ unsigned long signature; } ExceptionInfo; /* Exception typedef declarations. */ typedef void (*ErrorHandler)(const ExceptionType,const char *,const char *); typedef void (*FatalErrorHandler)(const ExceptionType,const char *,const char *) MAGICK_FUNC_NORETURN; typedef void (*WarningHandler)(const ExceptionType,const char *,const char *); /* Exception declarations. */ extern MagickExport const char *GetLocaleExceptionMessage(const ExceptionType,const char *), *GetLocaleMessage(const char *); extern MagickExport ErrorHandler SetErrorHandler(ErrorHandler); extern MagickExport FatalErrorHandler SetFatalErrorHandler(FatalErrorHandler); extern MagickExport void CatchException(const ExceptionInfo *), CopyException(ExceptionInfo *copy, const ExceptionInfo *original), DestroyExceptionInfo(ExceptionInfo *), GetExceptionInfo(ExceptionInfo *), MagickError(const ExceptionType,const char *,const char *), MagickFatalError(const ExceptionType,const char *,const char *) MAGICK_FUNC_NORETURN, MagickWarning(const ExceptionType,const char *,const char *), _MagickError(const ExceptionType,const char *,const char *), _MagickFatalError(const ExceptionType,const char *,const char *) MAGICK_FUNC_NORETURN, _MagickWarning(const ExceptionType,const char *,const char *), SetExceptionInfo(ExceptionInfo *,ExceptionType), ThrowException(ExceptionInfo *,const ExceptionType,const char *,const char *), ThrowLoggedException(ExceptionInfo *exception, const ExceptionType severity, const char *reason,const char *description,const char *module, const char *function,const unsigned long line); extern MagickExport WarningHandler SetWarningHandler(WarningHandler); /* Exception define definitions. */ #include #if defined(MAGICK_IMPLEMENTATION) # include "magick/error-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* !defined(_MAGICK_ERROR_H) */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/forward.h ================================================ /* Copyright (C) 2007 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Forward declarations for types used in public structures. */ #ifndef _MAGICK_FORWARD_H #define _MAGICK_FORWARD_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif typedef struct _Image *ImagePtr; typedef struct _Ascii85Info* _Ascii85InfoPtr_; typedef struct _BlobInfo* _BlobInfoPtr_; typedef struct _CacheInfo* _CacheInfoPtr_; typedef struct _ImageAttribute* _ImageAttributePtr_; typedef struct _SemaphoreInfo* _SemaphoreInfoPtr_; typedef struct _ThreadViewSet* _ThreadViewSetPtr_; typedef void *ViewInfo; #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_FORWARD_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/fx.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image FX Methods. */ #ifndef _MAGICK_FX_H #define _MAGICK_FX_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *CharcoalImage(const Image *,const double,const double,ExceptionInfo *), *ColorizeImage(const Image *,const char *,const PixelPacket,ExceptionInfo *), *ImplodeImage(const Image *,const double,ExceptionInfo *), *MorphImages(const Image *,const unsigned long,ExceptionInfo *), *OilPaintImage(const Image *,const double,ExceptionInfo *), *SteganoImage(const Image *,const Image *,ExceptionInfo *), *StereoImage(const Image *,const Image *,ExceptionInfo *), *SwirlImage(const Image *,double,ExceptionInfo *), *WaveImage(const Image *,const double,const double,ExceptionInfo *); extern MagickExport MagickPassFail ColorMatrixImage(Image *image,const unsigned int order,const double *matrix), SolarizeImage(Image *,const double); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_FX_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/gem.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Graphic Gems - Graphic Support Methods. */ #ifndef _MAGICK_GEM_H #define _MAGICK_GEM_H #include "magick/random.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Graphic gems define declarations. */ extern MagickExport double ExpandAffine(const AffineMatrix *), GenerateDifferentialNoise(const Quantum pixel,const NoiseType noise_type, MagickRandomKernel *kernel); extern MagickExport int GetOptimalKernelWidth(const double,const double), GetOptimalKernelWidth1D(const double,const double), GetOptimalKernelWidth2D(const double,const double); extern MagickExport Quantum GenerateNoise(const Quantum,const NoiseType); extern MagickExport void Contrast(const int,Quantum *,Quantum *,Quantum *), HSLTransform(const double,const double,const double,Quantum *,Quantum *, Quantum *), HWBTransform(const double,const double,const double,Quantum *,Quantum *, Quantum *), Hull(const long,const long,const unsigned long,const unsigned long,Quantum *, Quantum *,const int), IdentityAffine(AffineMatrix *), Modulate(const double,const double,const double,Quantum *,Quantum *, Quantum *), TransformHSL(const Quantum,const Quantum,const Quantum,double *,double *, double *), TransformHWB(const Quantum,const Quantum,const Quantum,double *,double *, double *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/gradient.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Gradient Image Methods. */ #ifndef _MAGICK_GRADIENT_H #define _MAGICK_GRADIENT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" extern MagickExport MagickPassFail GradientImage(Image *,const PixelPacket *,const PixelPacket *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_GRADIENT_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/hclut.h ================================================ /* Copyright (C) 2009 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Hald CLUT implementation */ #ifndef _MAGICK_HCLUT_H #define _MAGICK_HCLUT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport MagickPassFail HaldClutImage(Image *,const Image * clut); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_HCLUT_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/image.h ================================================ /* Copyright (C) 2003 - 2019 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Methods. */ #ifndef _MAGICK_IMAGE_H #define _MAGICK_IMAGE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/forward.h" #include "magick/colorspace.h" #include "magick/error.h" #include "magick/timer.h" /* Define declarations. */ #if !defined(QuantumDepth) # define QuantumDepth 16 #endif /* Maximum unsigned RGB value which fits in the specified bits If bits <= 0, then zero is returned. If bits exceeds bits in unsigned long, then max value of unsigned long is returned. */ #define MaxValueGivenBits(bits) ((unsigned long) \ (((int) bits <= 0) ? 0 : \ ((0x01UL << (Min(sizeof(unsigned long)*8U,(size_t)bits)-1)) + \ ((0x01UL << (Min(sizeof(unsigned long)*8U,(size_t)bits)-1))-1)))) #if (QuantumDepth == 8) # define MaxColormapSize 256U # define MaxMap 255U # define MaxMapDepth 8 # define MaxMapFloat 255.0f # define MaxMapDouble 255.0 # define MaxRGB 255U # define MaxRGBFloat 255.0f # define MaxRGBDouble 255.0 # define ScaleCharToMap(value) ((unsigned char) (value)) # define ScaleCharToQuantum(value) ((Quantum) (value)) # define ScaleLongToQuantum(value) ((Quantum) ((value)/16843009UL)) # define ScaleMapToChar(value) ((unsigned int) (value)) # define ScaleMapToQuantum(value) ((Quantum) (value)) # define ScaleQuantum(quantum) ((unsigned long) (quantum)) # define ScaleQuantumToChar(quantum) ((unsigned char) (quantum)) # define ScaleQuantumToLong(quantum) ((unsigned long) (16843009UL*(quantum))) # define ScaleQuantumToMap(quantum) ((unsigned char) (quantum)) # define ScaleQuantumToShort(quantum) ((unsigned short) (257U*(quantum))) # define ScaleShortToQuantum(value) ((Quantum) ((value)/257U)) # define ScaleToQuantum(value) ((unsigned long) (value)) # define ScaleQuantumToIndex(value) ((unsigned char) (value)) typedef unsigned char Quantum; #elif (QuantumDepth == 16) # define MaxColormapSize 65536U # define MaxMap 65535U # define MaxMapDepth 16 # define MaxMapFloat 65535.0f # define MaxMapDouble 65535.0 # define MaxRGB 65535U # define MaxRGBFloat 65535.0f # define MaxRGBDouble 65535.0 # define ScaleCharToMap(value) ((unsigned short) (257U*(value))) # define ScaleCharToQuantum(value) ((Quantum) (257U*(value))) # define ScaleLongToQuantum(value) ((Quantum) ((value)/65537UL)) # define ScaleMapToChar(value) ((unsigned int) ((value)/257U)) # define ScaleMapToQuantum(value) ((Quantum) (value)) # define ScaleQuantum(quantum) ((unsigned long) ((quantum)/257UL)) # define ScaleQuantumToChar(quantum) ((unsigned char) ((quantum)/257U)) # define ScaleQuantumToLong(quantum) ((unsigned long) (65537UL*(quantum))) # define ScaleQuantumToMap(quantum) ((unsigned short) (quantum)) # define ScaleQuantumToShort(quantum) ((unsigned short) (quantum)) # define ScaleShortToQuantum(value) ((Quantum) (value)) # define ScaleToQuantum(value) ((unsigned long) (257UL*(value))) # define ScaleQuantumToIndex(value) ((unsigned short) (value)) typedef unsigned short Quantum; #elif (QuantumDepth == 32) # define MaxColormapSize 65536U # define MaxRGB 4294967295U # define MaxRGBFloat 4294967295.0f # define MaxRGBDouble 4294967295.0 # define ScaleCharToQuantum(value) ((Quantum) (16843009U*(value))) # define ScaleLongToQuantum(value) ((Quantum) ((value))) # define ScaleQuantum(quantum) ((unsigned long) ((quantum)/16843009UL)) # define ScaleQuantumToChar(quantum) ((unsigned char) ((quantum)/16843009U)) # define ScaleQuantumToLong(quantum) ((unsigned long) (quantum)) # define ScaleQuantumToShort(quantum) ((unsigned short) ((quantum)/65537U)) # define ScaleShortToQuantum(value) ((Quantum) (65537U*(value))) # define ScaleToQuantum(value) ((unsigned long) (16843009UL*(value))) # define ScaleQuantumToIndex(value) ((unsigned short) ((value)/65537U)) /* MaxMap defines the maximum index value for algorithms which depend on lookup tables (e.g. colorspace transformations and normalization). When MaxMap is less than MaxRGB it is necessary to downscale samples to fit the range of MaxMap. The number of bits which are effectively preserved depends on the size of MaxMap. MaxMap should be a multiple of 255 and no larger than MaxRGB. Note that tables can become quite large and as the tables grow larger it may take more time to compute the table than to process the image. */ #define MaxMap 65535U #define MaxMapDepth 16 #define MaxMapFloat 65535.0f #define MaxMapDouble 65535.0 #if MaxMap == 65535U # define ScaleCharToMap(value) ((unsigned short) (257U*(value))) # define ScaleMapToChar(value) ((unsigned int) ((value)/257U)) # define ScaleMapToQuantum(value) ((Quantum) (65537U*(value))) # define ScaleQuantumToMap(quantum) ((unsigned short) ((quantum)/65537U)) #else # define ScaleCharToMap(value) ((unsigned short) ((MaxMap/255U)*(value))) # define ScaleMapToChar(value) ((unsigned int) ((value)/(MaxMap/255U))) # define ScaleMapToQuantum(value) ((Quantum) ((MaxRGB/MaxMap)*(value))) # define ScaleQuantumToMap(quantum) ((unsigned short) ((quantum)/(MaxRGB/MaxMap))) #endif typedef unsigned int Quantum; #else # error "Specified value of QuantumDepth is not supported" #endif #define OpaqueOpacity 0UL #define TransparentOpacity MaxRGB #define RoundDoubleToQuantum(value) ((Quantum) (value < 0.0 ? 0U : \ (value > MaxRGBDouble) ? MaxRGB : value + 0.5)) #define RoundFloatToQuantum(value) ((Quantum) (value < 0.0f ? 0U : \ (value > MaxRGBFloat) ? MaxRGB : value + 0.5f)) #define ConstrainToRange(min,max,value) (value < min ? min : \ (value > max) ? max : value) #define ConstrainToQuantum(value) ConstrainToRange(0,MaxRGB,value) #define ScaleAnyToQuantum(x,max_value) \ ((Quantum) (((double) MaxRGBDouble*x)/max_value+0.5)) #define MagickBoolToString(value) (value != MagickFalse ? "True" : "False") /* Return MagickTrue if channel is enabled in channels. Allows using code to adapt if ChannelType enumeration is changed to bit masks. */ #define MagickChannelEnabled(channels,channel) ((channels == AllChannels) || (channels == channel)) /* Deprecated defines. */ #define RunlengthEncodedCompression RLECompression #define RoundSignedToQuantum(value) RoundDoubleToQuantum(value) #define RoundToQuantum(value) RoundDoubleToQuantum(value) /* Enum declarations. */ typedef enum { UnspecifiedAlpha, AssociatedAlpha, UnassociatedAlpha } AlphaType; typedef enum { UndefinedChannel, RedChannel, /* RGB Red channel */ CyanChannel, /* CMYK Cyan channel */ GreenChannel, /* RGB Green channel */ MagentaChannel, /* CMYK Magenta channel */ BlueChannel, /* RGB Blue channel */ YellowChannel, /* CMYK Yellow channel */ OpacityChannel, /* Opacity channel */ BlackChannel, /* CMYK Black (K) channel */ MatteChannel, /* Same as Opacity channel (deprecated) */ AllChannels, /* Color channels */ GrayChannel /* Color channels represent an intensity. */ } ChannelType; typedef enum { UndefinedClass, DirectClass, PseudoClass } ClassType; typedef enum { UndefinedCompositeOp = 0, OverCompositeOp, InCompositeOp, OutCompositeOp, AtopCompositeOp, XorCompositeOp, PlusCompositeOp, MinusCompositeOp, AddCompositeOp, SubtractCompositeOp, DifferenceCompositeOp, MultiplyCompositeOp, BumpmapCompositeOp, CopyCompositeOp, CopyRedCompositeOp, CopyGreenCompositeOp, CopyBlueCompositeOp, CopyOpacityCompositeOp, ClearCompositeOp, DissolveCompositeOp, DisplaceCompositeOp, ModulateCompositeOp, ThresholdCompositeOp, NoCompositeOp, DarkenCompositeOp, LightenCompositeOp, HueCompositeOp, SaturateCompositeOp, ColorizeCompositeOp, LuminizeCompositeOp, ScreenCompositeOp, OverlayCompositeOp, CopyCyanCompositeOp, CopyMagentaCompositeOp, CopyYellowCompositeOp, CopyBlackCompositeOp, DivideCompositeOp, HardLightCompositeOp, ExclusionCompositeOp, ColorDodgeCompositeOp, ColorBurnCompositeOp, SoftLightCompositeOp, LinearBurnCompositeOp, LinearDodgeCompositeOp, LinearLightCompositeOp, VividLightCompositeOp, PinLightCompositeOp, HardMixCompositeOp } CompositeOperator; typedef enum { UndefinedCompression, NoCompression, BZipCompression, FaxCompression, Group3Compression = FaxCompression, Group4Compression, JPEGCompression, LosslessJPEGCompression, LZWCompression, RLECompression, ZipCompression, LZMACompression, /* Lempel-Ziv-Markov chain algorithm */ JPEG2000Compression, /* ISO/IEC std 15444-1 */ JBIG1Compression, /* ISO/IEC std 11544 / ITU-T rec T.82 */ JBIG2Compression, /* ISO/IEC std 14492 / ITU-T rec T.88 */ ZSTDCompression, /* Facebook's Zstandard compression */ WebPCompression /* Google's WebP compression */ } CompressionType; typedef enum { UndefinedDispose, NoneDispose, BackgroundDispose, PreviousDispose } DisposeType; typedef enum { UndefinedEndian, LSBEndian, /* "little" endian */ MSBEndian, /* "big" endian */ NativeEndian /* native endian */ } EndianType; typedef enum { UndefinedFilter, PointFilter, BoxFilter, TriangleFilter, HermiteFilter, HanningFilter, HammingFilter, BlackmanFilter, GaussianFilter, QuadraticFilter, CubicFilter, CatromFilter, MitchellFilter, LanczosFilter, BesselFilter, SincFilter } FilterTypes; typedef enum { #undef NoValue NoValue = 0x00000, #undef XValue XValue = 0x00001, #undef YValue YValue = 0x00002, #undef WidthValue WidthValue = 0x00004, #undef HeightValue HeightValue = 0x00008, #undef AllValues AllValues = 0x0000F, #undef XNegative XNegative = 0x00010, #undef YNegative YNegative = 0x00020, PercentValue = 0x01000, /* % */ AspectValue = 0x02000, /* ! */ LessValue = 0x04000, /* < */ GreaterValue = 0x08000, /* > */ AreaValue = 0x10000, /* @ */ MinimumValue = 0x20000 /* ^ */ } GeometryFlags; typedef enum { #undef ForgetGravity ForgetGravity, #undef NorthWestGravity NorthWestGravity, #undef NorthGravity NorthGravity, #undef NorthEastGravity NorthEastGravity, #undef WestGravity WestGravity, #undef CenterGravity CenterGravity, #undef EastGravity EastGravity, #undef SouthWestGravity SouthWestGravity, #undef SouthGravity SouthGravity, #undef SouthEastGravity SouthEastGravity, #undef StaticGravity StaticGravity } GravityType; typedef enum { UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, OptimizeType } ImageType; typedef enum { UndefinedInterlace, NoInterlace, LineInterlace, PlaneInterlace, PartitionInterlace } InterlaceType; typedef enum { UndefinedMode, FrameMode, UnframeMode, ConcatenateMode } MontageMode; typedef enum { UniformNoise, GaussianNoise, MultiplicativeGaussianNoise, ImpulseNoise, LaplacianNoise, PoissonNoise, /* Below added on 2012-03-17 */ RandomNoise, UndefinedNoise } NoiseType; /* Image orientation. Based on TIFF standard values (also EXIF). */ typedef enum /* Exif / Row 0 / Column 0 */ /* Orientation / edge / edge */ { /* ----------- / -------- / -------- */ UndefinedOrientation, /* 0 / Unknown / Unknown */ TopLeftOrientation, /* 1 / Left / Top */ TopRightOrientation, /* 2 / Right / Top */ BottomRightOrientation, /* 3 / Right / Bottom */ BottomLeftOrientation, /* 4 / Left / Bottom */ LeftTopOrientation, /* 5 / Top / Left */ RightTopOrientation, /* 6 / Top / Right */ RightBottomOrientation, /* 7 / Bottom / Right */ LeftBottomOrientation /* 8 / Bottom / Left */ } OrientationType; typedef enum { UndefinedPreview = 0, RotatePreview, ShearPreview, RollPreview, HuePreview, SaturationPreview, BrightnessPreview, GammaPreview, SpiffPreview, DullPreview, GrayscalePreview, QuantizePreview, DespecklePreview, ReduceNoisePreview, AddNoisePreview, SharpenPreview, BlurPreview, ThresholdPreview, EdgeDetectPreview, SpreadPreview, SolarizePreview, ShadePreview, RaisePreview, SegmentPreview, SwirlPreview, ImplodePreview, WavePreview, OilPaintPreview, CharcoalDrawingPreview, JPEGPreview } PreviewType; typedef enum { UndefinedIntent, SaturationIntent, PerceptualIntent, AbsoluteIntent, RelativeIntent } RenderingIntent; typedef enum { UndefinedResolution, PixelsPerInchResolution, PixelsPerCentimeterResolution } ResolutionType; /* Typedef declarations. */ typedef struct _AffineMatrix { double sx, rx, ry, sy, tx, ty; } AffineMatrix; typedef struct _PrimaryInfo { double x, y, z; } PrimaryInfo; typedef struct _ChromaticityInfo { PrimaryInfo red_primary, green_primary, blue_primary, white_point; } ChromaticityInfo; #if defined(MAGICK_IMPLEMENTATION) /* Useful macros for accessing PixelPacket members in a generic way. */ # define GetRedSample(p) ((p)->red) # define GetGreenSample(p) ((p)->green) # define GetBlueSample(p) ((p)->blue) # define GetOpacitySample(p) ((p)->opacity) # define SetRedSample(q,value) ((q)->red=(value)) # define SetGreenSample(q,value) ((q)->green=(value)) # define SetBlueSample(q,value) ((q)->blue=(value)) # define SetOpacitySample(q,value) ((q)->opacity=(value)) # define GetGraySample(p) ((p)->red) # define SetGraySample(q,value) ((q)->red=(q)->green=(q)->blue=(value)) # define GetYSample(p) ((p)->red) # define GetCbSample(p) ((p)->green) # define GetCrSample(p) ((p)->blue) # define SetYSample(q,value) ((q)->red=(value)) # define SetCbSample(q,value) ((q)->green=(value)) # define SetCrSample(q,value) ((q)->blue=(value)) # define GetCyanSample(p) ((p)->red) # define GetMagentaSample(p) ((p)->green) # define GetYellowSample(p) ((p)->blue) # define GetBlackSample(p) ((p)->opacity) # define SetCyanSample(q,value) ((q)->red=(value)) # define SetMagentaSample(q,value) ((q)->green=(value)) # define SetYellowSample(q,value) ((q)->blue=(value)) # define SetBlackSample(q,value) ((q)->opacity=(value)) # define ClearPixelPacket(q) ((q)->red=(q)->green=(q)->blue=(q)->opacity=0) #endif /* defined(MAGICK_IMPLEMENTATION) */ typedef struct _PixelPacket { #if defined(WORDS_BIGENDIAN) /* RGBA */ #define MAGICK_PIXELS_RGBA 1 Quantum red, green, blue, opacity; #else /* BGRA (as used by Microsoft Windows DIB) */ #define MAGICK_PIXELS_BGRA 1 Quantum blue, green, red, opacity; #endif } PixelPacket; typedef struct _DoublePixelPacket { double red, green, blue, opacity; } DoublePixelPacket; typedef struct _FloatPixelPacket { float red, green, blue, opacity; } FloatPixelPacket; /* ErrorInfo is used to record statistical difference (error) information based on computed Euclidean distance in RGB space. */ typedef struct _ErrorInfo { double mean_error_per_pixel, /* Average error per pixel (absolute range) */ normalized_mean_error, /* Average error per pixel (normalized to 1.0) */ normalized_maximum_error; /* Maximum error encountered (normalized to 1.0) */ } ErrorInfo; typedef struct _FrameInfo { unsigned long width, height; long x, y, inner_bevel, outer_bevel; } FrameInfo; typedef Quantum IndexPacket; typedef struct _LongPixelPacket { unsigned long red, green, blue, opacity; } LongPixelPacket; typedef struct _MontageInfo { char *geometry, *tile, *title, *frame, *texture, *font; double pointsize; unsigned long border_width; unsigned int shadow; PixelPacket fill, stroke, background_color, border_color, matte_color; GravityType gravity; char filename[MaxTextExtent]; unsigned long signature; } MontageInfo; typedef struct _ProfileInfo { size_t length; char *name; unsigned char *info; } ProfileInfo; typedef struct _RectangleInfo { unsigned long width, height; long x, y; } RectangleInfo; typedef struct _SegmentInfo { double x1, y1, x2, y2; } SegmentInfo; struct _ImageExtra; /* forward decl.; see member "extra" below */ typedef struct _Image { ClassType storage_class; /* DirectClass (TrueColor) or PseudoClass (colormapped) */ ColorspaceType colorspace; /* Current image colorspace/model */ CompressionType compression; /* Compression algorithm to use when encoding image */ MagickBool dither, /* True if image is to be dithered */ matte; /* True if image has an opacity (alpha) channel */ unsigned long columns, /* Number of image columns */ rows; /* Number of image rows */ unsigned int colors, /* Current number of colors in PseudoClass colormap */ depth; /* Bits of precision to preserve in color quantum */ PixelPacket *colormap; /* Pseudoclass colormap array */ PixelPacket background_color, /* Background color */ border_color, /* Border color */ matte_color; /* Matte (transparent) color */ double gamma; /* Image gamma (e.g. 0.45) */ ChromaticityInfo chromaticity; /* Red, green, blue, and white chromaticity values */ OrientationType orientation; /* Image orientation */ RenderingIntent rendering_intent; /* Rendering intent */ ResolutionType units; /* Units of image resolution (density) */ char *montage, /* Tile size and offset within an image montage */ *directory, /* Tile names from within an image montage */ *geometry; /* Composite/Crop options */ long offset; /* Offset to start of image data */ double x_resolution, /* Horizontal resolution (also see units) */ y_resolution; /* Vertical resolution (also see units) */ RectangleInfo page, /* Offset to apply when placing image */ tile_info; /* Subregion tile dimensions and offset */ double blur, /* Amount of blur to apply when zooming image */ fuzz; /* Colors within this distance match target color */ FilterTypes filter; /* Filter to use when zooming image */ InterlaceType interlace; /* Interlace pattern to use when writing image */ EndianType endian; /* Byte order to use when writing image */ GravityType gravity; /* Image placement gravity */ CompositeOperator compose; /* Image placement composition (default OverCompositeOp) */ DisposeType dispose; /* GIF disposal option */ unsigned long scene, /* Animation frame scene number */ delay, /* Animation frame scene delay */ iterations, /* Animation iterations */ total_colors; /* Number of unique colors. See GetNumberColors() */ long start_loop; /* Animation frame number to start looping at */ ErrorInfo error; /* Computed image comparison or quantization error */ TimerInfo timer; /* Operation micro-timer */ void *client_data; /* User specified opaque data pointer */ /* Output file name. A colon delimited format identifier may be prepended to the file name in order to force a particular output format. Otherwise the file extension is used. If no format prefix or file extension is present, then the output format is determined by the 'magick' field. */ char filename[MaxTextExtent]; /* Original file name (name of input image file) */ char magick_filename[MaxTextExtent]; /* File format of the input file, and the default output format. The precedence when selecting the output format is: 1) magick prefix to file name (e.g. "jpeg:foo). 2) file name extension. (e.g. "foo.jpg") 3) content of this magick field. */ char magick[MaxTextExtent]; /* Original image width (before transformations) */ unsigned long magick_columns; /* Original image height (before transformations) */ unsigned long magick_rows; ExceptionInfo exception; /* Any error associated with this image frame */ struct _Image *previous, /* Pointer to previous frame */ *next; /* Pointer to next frame */ /* To be added here for a later release: quality? subsampling video black/white setup levels (ReferenceBlack/ReferenceWhite) sample format (integer/float) */ /* Only private members appear past this point */ void /* Private, Embedded profiles */ *profiles; unsigned int is_monochrome, /* Private, True if image is known to be monochrome */ is_grayscale, /* Private, True if image is known to be grayscale */ taint; /* Private, True if image has not been modifed */ /* Allow for expansion of Image without increasing its size. The internals are defined only in image.c. Clients outside of image.c can access the internals via the provided access functions (see below). This location in Image used to be occupied by Image *clip_mask. The clip_mask member now lives in _ImageExtra. */ struct _ImageExtra *extra; MagickBool ping; /* Private, if true, pixels are undefined */ _CacheInfoPtr_ cache; /* Private, image pixel cache */ _ThreadViewSetPtr_ default_views; /* Private, default cache views */ _ImageAttributePtr_ attributes; /* Private, Image attribute list */ _Ascii85InfoPtr_ ascii85; /* Private, supports huffman encoding */ _BlobInfoPtr_ blob; /* Private, file I/O object */ long reference_count; /* Private, Image reference count */ _SemaphoreInfoPtr_ semaphore; /* Private, Per image lock (for reference count) */ unsigned int logging; /* Private, True if logging is enabled */ struct _Image *list; /* Private, used only by display */ unsigned long signature; /* Private, Unique code to validate structure */ } Image; typedef struct _ImageInfo { CompressionType compression; /* Image compression to use while decoding */ MagickBool temporary, /* Remove file "filename" once it has been read. */ adjoin, /* If True, join multiple frames into one file */ antialias; /* If True, antialias while rendering */ unsigned long subimage, /* Starting image scene ID to select */ subrange, /* Span of image scene IDs (from starting scene) to select */ depth; /* Number of quantum bits to preserve while encoding */ char *size, /* Desired/known dimensions to use when decoding image */ *tile, /* Deprecated, name of image to tile on background */ *page; /* Output page size & offset */ InterlaceType interlace; /* Interlace scheme to use when decoding image */ EndianType endian; /* Select MSB/LSB endian output for TIFF format */ ResolutionType units; /* Units to apply when evaluating the density option */ unsigned long quality; /* Compression quality factor (format specific) */ char *sampling_factor, /* JPEG, MPEG, and YUV chroma downsample factor */ *server_name, /* X11 server display specification */ *font, /* Font name to use for text annotations */ *texture, /* Name of texture image to use for background fills */ *density; /* Image resolution (also see units) */ double pointsize; /* Font pointsize */ double fuzz; /* Colors within this distance are a match */ PixelPacket pen, /* Stroke or fill color while drawing */ background_color, /* Background color */ border_color, /* Border color (color surrounding frame) */ matte_color; /* Matte color (frame color) */ MagickBool dither, /* If true, dither image while writing */ monochrome, /* If true, use monochrome format */ progress; /* If true, show progress indication */ ColorspaceType colorspace; /* Colorspace representations of image pixels */ ImageType type; /* Desired image type (used while reading or writing) */ long group; /* X11 window group ID */ unsigned int verbose; /* If non-zero, display high-level processing */ char *view, /* FlashPIX view specification */ *authenticate; /* Password used to decrypt file */ void *client_data; /* User-specified data to pass to coder */ FILE *file; /* If not null, stdio FILE * to read image from (fopen mode "rb") or write image to (fopen mode "rb+"). */ char magick[MaxTextExtent], /* File format to read. Overrides file extension */ filename[MaxTextExtent]; /* File name to read */ /* Only private members appear past this point */ _CacheInfoPtr_ cache; /* Private. Used to pass image via open cache */ void *definitions; /* Private. Map of coder specific options passed by user. Use AddDefinitions, RemoveDefinitions, & AccessDefinition to access and manipulate this data. */ Image *attributes; /* Private. Image attribute list */ MagickBool ping; /* Private, if true, read file header only */ PreviewType preview_type; /* Private, used by PreviewImage */ MagickBool affirm; /* Private, when true do not intuit image format */ _BlobInfoPtr_ blob; /* Private, used to pass in open blob */ size_t length; /* Private, used to pass in open blob length */ char unique[MaxTextExtent], /* Private, passes temporary filename to TranslateText */ zero[MaxTextExtent]; /* Private, passes temporary filename to TranslateText */ unsigned long signature; /* Private, used to validate structure */ } ImageInfo; /* Image utilities methods. */ extern MagickExport ExceptionType CatchImageException(Image *); extern MagickExport Image *AllocateImage(const ImageInfo *), *AppendImages(const Image *,const unsigned int,ExceptionInfo *), *CloneImage(const Image *,const unsigned long,const unsigned long, const unsigned int,ExceptionInfo *), *GetImageClipMask(const Image *,ExceptionInfo *), *GetImageCompositeMask(const Image *,ExceptionInfo *), /*to support SVG masks*/ *ReferenceImage(Image *); extern MagickExport ImageInfo *CloneImageInfo(const ImageInfo *); extern MagickExport const char *AccessDefinition(const ImageInfo *image_info,const char *magick, const char *key); extern MagickExport int GetImageGeometry(const Image *,const char *,const unsigned int, RectangleInfo *); /* Functions which return unsigned int as a True/False boolean value */ extern MagickExport MagickBool IsTaintImage(const Image *), IsSubimage(const char *,const MagickBool); /* Functions which return unsigned int to indicate operation pass/fail */ extern MagickExport MagickPassFail AddDefinition(ImageInfo *image_info,const char *magick, const char *key, const char *value, ExceptionInfo *exception), AddDefinitions(ImageInfo *image_info,const char *options, ExceptionInfo *exception), AnimateImages(const ImageInfo *image_info,Image *image), ClipImage(Image *image), ClipPathImage(Image *image,const char *pathname,const MagickBool inside), CompositeMaskImage(Image *image), /*to support SVG masks*/ CompositePathImage(Image *image,const char *pathname,const MagickBool inside), /*to support SVG masks*/ DisplayImages(const ImageInfo *image_info,Image *image), RemoveDefinitions(const ImageInfo *image_info,const char *options), ResetImagePage(Image *image,const char *page), SetImage(Image *image,const Quantum), SetImageEx(Image *image,const Quantum opacity,ExceptionInfo *exception), SetImageColor(Image *image,const PixelPacket *pixel), SetImageColorRegion(Image *image,long x,long y,unsigned long width, unsigned long height,const PixelPacket *pixel), SetImageClipMask(Image *image,const Image *clip_mask), SetImageCompositeMask(Image *image,const Image *composite_mask), /*to support SVG masks*/ SetImageDepth(Image *image,const unsigned long), SetImageInfo(ImageInfo *image_info,const unsigned int flags,ExceptionInfo *exception), SetImageType(Image *image,const ImageType), StripImage(Image *image), SyncImage(Image *image); extern MagickExport void AllocateNextImage(const ImageInfo *,Image *), DestroyImage(Image *), DestroyImageInfo(ImageInfo *), GetImageException(Image *,ExceptionInfo *), GetImageInfo(ImageInfo *), ModifyImage(Image **,ExceptionInfo *), SetImageOpacity(Image *,const unsigned int); /* provide public access to the clip_mask member of Image */ extern MagickExport Image **ImageGetClipMask(const Image *) MAGICK_FUNC_PURE; /* provide public access to the composite_mask member of Image */ extern MagickExport Image **ImageGetCompositeMask(const Image *) MAGICK_FUNC_PURE; #if defined(MAGICK_IMPLEMENTATION) /* SetImageInfo flags specification. */ # define SETMAGICK_FALSE 0x00000 /* MagickFalse ("read") */ # define SETMAGICK_TRUE 0x00001 /* MagickTrue ("write+rectify") */ # define SETMAGICK_READ 0x00002 /* Filespec will be read */ # define SETMAGICK_WRITE 0x00004 /* Filespec will be written */ # define SETMAGICK_RECTIFY 0x00008 /* Look for adjoin in filespec */ #include "magick/image-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_IMAGE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/list.h ================================================ /* Copyright (C) 2003-2018 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image List Methods. */ #ifndef _MAGICK_LIST_H #define _MAGICK_LIST_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif extern MagickExport Image *CloneImageList(const Image *,ExceptionInfo *), *GetFirstImageInList(const Image *) MAGICK_FUNC_PURE, *GetImageFromList(const Image *,const long) MAGICK_FUNC_PURE, *GetLastImageInList(const Image *) MAGICK_FUNC_PURE, *GetNextImageInList(const Image *) MAGICK_FUNC_PURE, *GetPreviousImageInList(const Image *) MAGICK_FUNC_PURE, **ImageListToArray(const Image *,ExceptionInfo *), *NewImageList(void) MAGICK_FUNC_CONST, *RemoveLastImageFromList(Image **), *RemoveFirstImageFromList(Image **), *SplitImageList(Image *), *SyncNextImageInList(const Image *); extern MagickExport long GetImageIndexInList(const Image *) MAGICK_FUNC_PURE; extern MagickExport unsigned long GetImageListLength(const Image *) MAGICK_FUNC_PURE; extern MagickExport void AppendImageToList(Image **,Image *), DeleteImageFromList(Image **), DestroyImageList(Image *), InsertImageInList(Image **,Image *), PrependImageToList(Image **,Image *), ReplaceImageInList(Image **images,Image *image), ReverseImageList(Image **), SpliceImageIntoList(Image **,const unsigned long,Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/log.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Log methods. */ #ifndef _MAGICK_LOG_H #define _MAGICK_LOG_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Define declarations. */ #define MagickLogFilename "log.mgk" /* Obtain the current C function name (if possible) */ # if !defined(GetCurrentFunction) # if (((defined(__cplusplus) || defined(c_plusplus)) && defined(HAS_CPP__func__)) || \ (!(defined(__cplusplus) || defined(c_plusplus)) && defined(HAS_C__func__))) # define GetCurrentFunction() (__func__) # elif defined(_VISUALC_) && defined(__FUNCTION__) # define GetCurrentFunction() (__FUNCTION__) # else # define GetCurrentFunction() ("unknown") # endif # endif /* Obtain current source file, function name, and source file line, in a form acceptable for use with LogMagickEvent. */ # if !defined(GetMagickModule) # define GetMagickModule() __FILE__,GetCurrentFunction(),__LINE__ # endif /* NOTE: any changes to this effect PerlMagick */ typedef enum { UndefinedEventMask = 0x00000000, NoEventsMask = 0x00000000, ConfigureEventMask = 0x00000001, AnnotateEventMask = 0x00000002, RenderEventMask = 0x00000004, TransformEventMask = 0x00000008, LocaleEventMask = 0x00000010, CoderEventMask = 0x00000020, X11EventMask = 0x00000040, CacheEventMask = 0x00000080, BlobEventMask = 0x00000100, DeprecateEventMask = 0x00000200, UserEventMask = 0x00000400, ResourceEventMask = 0x00000800, TemporaryFileEventMask = 0x00001000, /* ExceptionEventMask = WarningEventMask | ErrorEventMask | FatalErrorEventMask */ ExceptionEventMask = 0x00070000, OptionEventMask = 0x00004000, InformationEventMask = 0x00008000, WarningEventMask = 0x00010000, ErrorEventMask = 0x00020000, FatalErrorEventMask = 0x00040000, AllEventsMask = 0x7FFFFFFF } LogEventType; typedef void (*LogMethod)(const ExceptionType,const char *); /* Method declarations. */ extern MagickExport MagickBool IsEventLogging(void) MAGICK_FUNC_PURE, LogMagickEvent(const ExceptionType type, const char *module,const char *function,const unsigned long line, const char *format,...) MAGICK_ATTRIBUTE((__format__ (__printf__,5,6))), LogMagickEventList(const ExceptionType type, const char *module,const char *function,const unsigned long line, const char *format,va_list operands) MAGICK_ATTRIBUTE((__format__ (__printf__,5,0))); extern MagickExport unsigned long SetLogEventMask(const char *events); extern MagickExport void SetLogFormat(const char *format), SetLogMethod(LogMethod); #if defined(MAGICK_IMPLEMENTATION) # include "magick/log-private.h" #endif /* MAGICK_IMPLEMENTATION */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_LOG_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/magic.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Magic methods. */ #ifndef _MAGICK_MAGIC_H #define _MAGICK_MAGIC_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Method declarations. */ extern MagickExport MagickPassFail GetMagickFileFormat(const unsigned char *header,const size_t header_length, char *format,const size_t format_length,ExceptionInfo *exception), ListMagicInfo(FILE *file,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) # include "magick/magic-private.h" #endif /* MAGICK_IMPLEMENTATION */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_MAGIC_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/magick.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Application Programming Interface declarations. */ #ifndef _MAGICK_MAGICK_H #define _MAGICK_MAGICK_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Flags to form options passed to InitializeMagickEx */ #define MAGICK_OPT_NO_SIGNAL_HANDER 0x0001 /* Don't register ANSI/POSIX signal handlers */ typedef Image *(*DecoderHandler)(const ImageInfo *,ExceptionInfo *); typedef unsigned int (*EncoderHandler)(const ImageInfo *,Image *), (*MagickHandler)(const unsigned char *,const size_t); /* Stability and usefulness of the coder. */ typedef enum { BrokenCoderClass = -1, /* Known to sometimes/often not work properly or might not be useful at all */ UnstableCoderClass = 0, /* Weak implementation, poorly designed file format, and/or hardly ever used */ StableCoderClass, /* Well maintained, but not often used */ PrimaryCoderClass /* Well maintained and commonly used */ } CoderClass; /* How the file extension should be treated (e.g. in SetImageInfo()). */ typedef enum { HintExtensionTreatment = 0, /* Extension is a useful hint to indicate format */ ObeyExtensionTreatment, /* Extension must be obeyed as format indicator */ IgnoreExtensionTreatment /* Format has no associated extension */ } ExtensionTreatment; typedef struct _MagickInfo { struct _MagickInfo *next, /* private, next member in list */ *previous; /* private, previous member in list */ const char *name; /* format ID ("magick") */ const char *description, /* format description */ *note, /* usage note for user */ *version, /* support library version */ *module; /* name of loadable module */ DecoderHandler decoder; /* function vector to decoding routine */ EncoderHandler encoder; /* function vector to encoding routine */ MagickHandler magick; /* function vector to format test routine */ void *client_data; /* arbitrary user supplied data */ MagickBool adjoin, /* coder may read/write multiple frames (default True) */ raw, /* coder requires that size be set (default False) */ stealth, /* coder should not appear in formats listing (default MagickFalse) */ seekable_stream, /* coder requires BLOB "seek" and "tell" APIs (default MagickFalse) * Note that SetImageInfo() currently always copies input * from a pipe, .gz, or .bz2 file, to a temporary file so * that it can retrieve a bit of the file header in order to * support the file header magic logic. */ blob_support, /* coder uses BLOB APIs (default True) */ thread_support; /* coder is thread safe (default True) */ CoderClass coder_class; /* Coder usefulness/stability level */ ExtensionTreatment extension_treatment; /* How much faith should be placed on file extension? */ unsigned long signature; /* private, structure validator */ } MagickInfo; /* Magick method declaractions. */ extern MagickExport char *MagickToMime(const char *magick); extern MagickExport const char *GetImageMagick(const unsigned char *magick,const size_t length); extern MagickExport MagickBool IsMagickConflict(const char *magick) MAGICK_FUNC_PURE; extern MagickExport MagickPassFail ListModuleMap(FILE *file,ExceptionInfo *exception), ListMagickInfo(FILE *file,ExceptionInfo *exception), InitializeMagickEx(const char *path, unsigned int options, ExceptionInfo *exception), UnregisterMagickInfo(const char *name); extern MagickExport void DestroyMagick(void), InitializeMagick(const char *path), PanicDestroyMagick(void); extern MagickExport const MagickInfo *GetMagickInfo(const char *name,ExceptionInfo *exception); extern MagickExport MagickInfo **GetMagickInfoArray(ExceptionInfo *exception); extern MagickExport MagickInfo *RegisterMagickInfo(MagickInfo *magick_info), *SetMagickInfo(const char *name); #if defined(MAGICK_IMPLEMENTATION) # include "magick/magick-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_MAGICK_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/magick_config.h ================================================ /* magick/magick_config_api.h. Generated from magick_config_api.h.in by configure. */ /* Defines required by */ /* Define if you have X11 library */ /* #undef HasX11 */ /* Number of bits in a pixel Quantum (8/16/32) */ #define QuantumDepth 8 /* Define to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel and VAX). */ /* #undef WORDS_BIGENDIAN */ /* Prefix Magick library symbols with a common string. */ /* #undef PREFIX_MAGICK_SYMBOLS */ /* Define to `unsigned int' if does not define. */ /* #undef size_t */ /* Define to `int' if does not define. */ /* #undef ssize_t */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/magick_types.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick types typedefs. GraphicsMagick is expected to compile with any C '89 ANSI C compiler supporting at least 16-bit 'short', 32-bit 'int', and 32-bit 'long'. It is also expected to take advantage of 64-bit LP64 and Windows WIN64 LLP64. We use C '99 style types but declare our own types so as to not depend on C '99 header files, and take care to depend only on C '89 library functions, POSIX, or well-known extensions. Any C '99 syntax used is removed if the compiler does not support it. */ #ifndef _MAGICK_TYPES_H #define _MAGICK_TYPES_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Assign ANSI C'99 stdint.h-like typedefs based on the sizes of native types magick_int8_t -- -128 to 127 magick_uint8_t -- 0 to 255 magick_int16_t -- -32,768 to 32,767 magick_uint16_t -- 0 to 65,535 magick_int32_t -- -2,147,483,648 to 2,147,483,647 magick_uint32_t -- 0 to 4,294,967,295 magick_int64_t -- -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807 magick_uint64_t -- 0 to 18,446,744,073,709,551,615 magick_uintmax_t -- largest native unsigned integer type ("%ju") 0 to UINTMAX_MAX UINTMAX_C(value) declares constant value magick_uintptr_t -- unsigned type for storing a pointer value ("%tu") 0 to UINTPTR_MAX ANSI C '89 stddef.h-like types size_t -- unsigned type representing sizes of objects ("%zu") 0 to SIZE_MAX ptrdiff_t -- signed type for subtracting two pointers ("%td") PTRDIFF_MIN to PTRDIFF_MAX IEEE Std 1003.1 (1990), 2004 types. Not part of ANSI C! ssize_t -- signed type for a count of bytes or an error indication ("%zd") ? to SSIZE_MAX */ #if (defined(WIN32) || defined(WIN64)) && \ !defined(__MINGW32__) && !defined(__MINGW64__) /* The following typedefs are used for WIN32 & WIN64 (without configure) */ typedef signed char magick_int8_t; typedef unsigned char magick_uint8_t; typedef signed short magick_int16_t; typedef unsigned short magick_uint16_t; typedef signed int magick_int32_t; # define MAGICK_INT32_F "" typedef unsigned int magick_uint32_t; # define MAGICK_UINT32_F "" typedef signed __int64 magick_int64_t; # define MAGICK_INT64_F "I64" typedef unsigned __int64 magick_uint64_t; # define MAGICK_UINT64_F "I64" typedef magick_uint64_t magick_uintmax_t; # if defined(WIN64) /* WIN64 uses the LLP64 model */ typedef unsigned long long magick_uintptr_t; # define MAGICK_SIZE_T_F "I64" # define MAGICK_SIZE_T unsigned __int64 # define MAGICK_SSIZE_T_F "I64" # define MAGICK_SSIZE_T signed __int64 # else typedef unsigned long magick_uintptr_t; # define MAGICK_SIZE_T_F "l" # define MAGICK_SIZE_T unsigned long # define MAGICK_SSIZE_T_F "l" # define MAGICK_SSIZE_T long # endif // defined(WIN64) #else /* The following typedefs are subtituted when using Unixish configure */ typedef signed char magick_int8_t; typedef unsigned char magick_uint8_t; typedef signed short magick_int16_t; typedef unsigned short magick_uint16_t; typedef signed int magick_int32_t; # define MAGICK_INT32_F "" typedef unsigned int magick_uint32_t; # define MAGICK_UINT32_F "" typedef signed long magick_int64_t; # define MAGICK_INT64_F "l" typedef unsigned long magick_uint64_t; # define MAGICK_UINT64_F "l" typedef unsigned long magick_uintmax_t; # define MAGICK_UINTMAX_F "l" typedef unsigned long magick_uintptr_t; # define MAGICK_UINTPTR_F "l" # define MAGICK_SIZE_T_F "l" # define MAGICK_SIZE_T unsigned long # define MAGICK_SSIZE_T_F "l" # define MAGICK_SSIZE_T signed long #endif /* 64-bit file and blob offset type */ typedef magick_int64_t magick_off_t; #define MAGICK_OFF_F MAGICK_INT64_F #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_TYPES_H */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/memory.h ================================================ /* Copyright (C) 2003-2020 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Memory Allocation Methods. */ #ifndef _MAGICK_MEMORY_H #define _MAGICK_MEMORY_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif typedef void *(*MagickMallocFunc)(size_t size); typedef void (*MagickFreeFunc)(void *ptr); typedef void *(*MagickReallocFunc)(void *ptr, size_t size); extern MagickExport void MagickAllocFunctions(MagickFreeFunc free_func,MagickMallocFunc malloc_func, MagickReallocFunc realloc_func), *MagickMalloc(const size_t size) MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(1), *MagickMallocAligned(const size_t alignment, const size_t size) MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(2), *MagickMallocCleared(const size_t size) MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(1), *MagickCloneMemory(void *destination,const void *source,const size_t size) MAGICK_FUNC_NONNULL, *MagickRealloc(void *memory,const size_t size) MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(2), MagickFree(void *memory), MagickFreeAligned(void *memory); #if defined(MAGICK_IMPLEMENTATION) #include "magick/memory-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/module.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Modules Methods. */ #ifndef _MAGICK_MODULE_H #define _MAGICK_MODULE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Modules declarations. */ extern MagickExport MagickPassFail ExecuteModuleProcess(const char *tag,Image **image, const int argc,char **argv); #if defined(MAGICK_IMPLEMENTATION) #include "magick/module-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/monitor.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Progress Monitor Methods. */ #ifndef _MAGICK_MONITOR_H #define _MAGICK_MONITOR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Monitor typedef declarations. */ typedef MagickPassFail (*MonitorHandler)(const char *text,const magick_int64_t quantum, const magick_uint64_t span,ExceptionInfo *exception); /* Monitor declarations. */ extern MagickExport MonitorHandler SetMonitorHandler(MonitorHandler handler); extern MagickExport MagickPassFail MagickMonitor(const char *text, const magick_int64_t quantum,const magick_uint64_t span, ExceptionInfo *exception) MAGICK_FUNC_DEPRECATED; extern MagickExport MagickPassFail MagickMonitorFormatted(const magick_int64_t quantum, const magick_uint64_t span, ExceptionInfo *exception, const char *format,...) MAGICK_ATTRIBUTE((__format__ (__printf__,4,5))); #if defined(MAGICK_IMPLEMENTATION) # include "magick/monitor-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/montage.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Montage Methods. */ #ifndef _MAGICK_MONTAGE_H #define _MAGICK_MONTAGE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *MontageImages(const Image *,const MontageInfo *,ExceptionInfo *); extern MagickExport MontageInfo *CloneMontageInfo(const ImageInfo *,const MontageInfo *); extern MagickExport void DestroyMontageInfo(MontageInfo *), GetMontageInfo(const ImageInfo *,MontageInfo *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_MONTAGE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/operator.h ================================================ /* % Copyright (C) 2004 - 2012 GraphicsMagick Group % % This program is covered by multiple licenses, which are described in % Copyright.txt. You should have received a copy of Copyright.txt with this % package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. % % Interfaces to support quantum operators. % Written by Bob Friesenhahn, March 2004. % */ #ifndef _MAGICK_OPERATOR_H #define _MAGICK_OPERATOR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ typedef enum { UndefinedQuantumOp = 0, AddQuantumOp, /* Add value */ AndQuantumOp, /* Bitwise AND value */ AssignQuantumOp, /* Direct value assignment */ DivideQuantumOp, /* Divide by value */ LShiftQuantumOp, /* Bitwise left-shift value N bits */ MultiplyQuantumOp, /* Multiply by value */ OrQuantumOp, /* Bitwise OR value */ RShiftQuantumOp, /* Bitwise right shift value */ SubtractQuantumOp, /* Subtract value */ ThresholdQuantumOp, /* Above threshold white, otherwise black */ ThresholdBlackQuantumOp, /* Below threshold is black */ ThresholdWhiteQuantumOp, /* Above threshold is white */ XorQuantumOp, /* Bitwise XOR value */ NoiseGaussianQuantumOp, /* Gaussian noise */ NoiseImpulseQuantumOp, /* Impulse noise */ NoiseLaplacianQuantumOp, /* Laplacian noise */ NoiseMultiplicativeQuantumOp, /* Multiplicative gaussian noise */ NoisePoissonQuantumOp, /* Poisson noise */ NoiseUniformQuantumOp, /* Uniform noise */ NegateQuantumOp, /* Negate (invert) channel, ignore value */ GammaQuantumOp, /* Adjust image gamma */ DepthQuantumOp, /* Adjust image depth */ /* Below added on 2008-12-13 */ LogQuantumOp, /* log(quantum*value+1)/log(value+1) */ MaxQuantumOp, /* Assign value if > quantum */ MinQuantumOp, /* Assign value if < quantum */ PowQuantumOp, /* Power function: pow(quantum,value) */ /* Below added on 2012-03-17 */ NoiseRandomQuantumOp, /* Random noise */ /* Below added on 2014-05-17 */ ThresholdBlackNegateQuantumOp, /* Below threshold is set to white */ ThresholdWhiteNegateQuantumOp /* Above threshold is set to black */ } QuantumOperator; extern MagickExport MagickPassFail QuantumOperatorImage(Image *image,const ChannelType channel, const QuantumOperator quantum_operator,const double rvalue, ExceptionInfo *exception), QuantumOperatorImageMultivalue(Image *image, const QuantumOperator quantum_operator, const char *values), QuantumOperatorRegionImage(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows, const ChannelType channel,const QuantumOperator quantum_operator, const double rvalue,ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/paint.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Paint Methods. */ #ifndef _MAGICK_PAINT_H #define _MAGICK_PAINT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/render.h" extern MagickExport unsigned int ColorFloodfillImage(Image *,const DrawInfo *,const PixelPacket,const long, const long,const PaintMethod), MatteFloodfillImage(Image *,const PixelPacket,const unsigned int,const long, const long,const PaintMethod); extern MagickExport unsigned int OpaqueImage(Image *,const PixelPacket,const PixelPacket), TransparentImage(Image *,const PixelPacket,const unsigned int); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/pixel_cache.h ================================================ /* Copyright (C) 2003 - 2018 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Pixel Cache Methods. */ #ifndef _MAGICK_CACHE_H #define _MAGICK_CACHE_H #include "magick/forward.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declaractions. */ typedef enum { UndefinedVirtualPixelMethod, ConstantVirtualPixelMethod, EdgeVirtualPixelMethod, MirrorVirtualPixelMethod, TileVirtualPixelMethod } VirtualPixelMethod; /* Typedef declaractions. */ typedef _CacheInfoPtr_ Cache; /***** * * Default View interfaces * *****/ /* Read only access to a rectangular pixel region. */ MagickExport const PixelPacket *AcquireImagePixels(const Image *image,const long x,const long y, const unsigned long columns, const unsigned long rows,ExceptionInfo *exception); /* AccessImmutableIndexes() returns the read-only indexes associated with a rectangular pixel region already selected via AcquireImagePixels(). */ extern MagickExport const IndexPacket *AccessImmutableIndexes(const Image *image); /* Return one DirectClass pixel at the the specified (x,y) location. Similar function as GetOnePixel(). Note that the value returned by GetIndexes() may or may not be influenced by this function. */ extern MagickExport PixelPacket AcquireOnePixel(const Image *image,const long x,const long y, ExceptionInfo *exception); /* GetImagePixels() and GetImagePixelsEx() obtains a pixel region for read/write access. */ extern MagickExport PixelPacket *GetImagePixels(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows); extern MagickExport PixelPacket *GetImagePixelsEx(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows, ExceptionInfo *exception); /* GetImageVirtualPixelMethod() gets the "virtual pixels" method for the image. */ extern MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) MAGICK_FUNC_PURE; /* GetPixels() and AccessMutablePixels() return the pixels associated with the last call to SetImagePixels() or GetImagePixels(). */ extern MagickExport PixelPacket *GetPixels(const Image *image) MAGICK_FUNC_DEPRECATED; /* Prefer AccessMutablePixels instead */ extern MagickExport PixelPacket *AccessMutablePixels(Image *image); /* GetIndexes() and AccessMutableIndexes() return the colormap indexes associated with the last call to SetImagePixels() or GetImagePixels(). */ extern MagickExport IndexPacket *GetIndexes(const Image *image) MAGICK_FUNC_DEPRECATED; /* Prefer AccessMutableIndexes() instead */ extern MagickExport IndexPacket *AccessMutableIndexes(Image *image); /* GetOnePixel() returns a single DirectClass pixel at the specified (x,y) location. Similar to AcquireOnePixel(). It is preferred to use AcquireOnePixel() since it allows reporting to a specified exception structure. Note that the value returned by GetIndexes() is not reliably influenced by this function. */ extern MagickExport PixelPacket GetOnePixel(Image *image,const long x,const long y) MAGICK_FUNC_DEPRECATED; /* Prefer AcquireOnePixel() instead */ /* GetPixelCacheArea() returns the area (width * height in pixels) consumed by the current pixel cache. */ extern MagickExport magick_off_t GetPixelCacheArea(const Image *image); /* SetImagePixels() and SetImagePixelsEx() initialize a pixel region for write-only access. */ extern MagickExport PixelPacket *SetImagePixels(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows); extern MagickExport PixelPacket *SetImagePixelsEx(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows, ExceptionInfo *exception); /* SetImageVirtualPixelMethod() sets the "virtual pixels" method for the image. */ extern MagickExport MagickPassFail SetImageVirtualPixelMethod(const Image *image, const VirtualPixelMethod method); /* SyncImagePixels() and SyncImagePixelsEx() save the image pixels to the in-memory or disk cache. */ extern MagickExport MagickPassFail SyncImagePixels(Image *image); extern MagickExport MagickPassFail SyncImagePixelsEx(Image *image,ExceptionInfo *exception); /**** * * Cache view interfaces * ****/ /* OpenCacheView() opens a cache view. */ extern MagickExport ViewInfo *OpenCacheView(Image *image); /* CloseCacheView() closes a cache view. */ extern MagickExport void CloseCacheView(ViewInfo *view); /* AccessCacheViewPixels() returns the pixels associated with the last request to select a view pixel region (i.e. AcquireCacheViewPixels() or GetCacheViewPixels()). */ extern MagickExport PixelPacket *AccessCacheViewPixels(const ViewInfo *view) MAGICK_FUNC_PURE; /* AcquireCacheViewIndexes() returns read-only indexes associated with a cache view. */ extern MagickExport const IndexPacket *AcquireCacheViewIndexes(const ViewInfo *view) MAGICK_FUNC_PURE; /* AcquireCacheViewPixels() obtains a pixel region from a cache view for read-only access. */ extern MagickExport const PixelPacket *AcquireCacheViewPixels(ViewInfo *view, const long x,const long y, const unsigned long columns, const unsigned long rows, ExceptionInfo *exception); /* AcquireOneCacheViewPixel() returns one DirectClass pixel from a cache view. Note that the value returned by GetCacheViewIndexes() is not reliably influenced by this function. */ extern MagickExport MagickPassFail AcquireOneCacheViewPixel(ViewInfo *view,PixelPacket *pixel, const long x,const long y,ExceptionInfo *exception); /* GetCacheViewArea() returns the area (width * height in pixels) currently consumed by the pixel cache view. */ extern MagickExport magick_off_t GetCacheViewArea(const ViewInfo *view) MAGICK_FUNC_PURE; /* GetCacheViewImage() obtains the image used to allocate the cache view. */ extern Image * GetCacheViewImage(const ViewInfo *view) MAGICK_FUNC_PURE; /* GetCacheViewIndexes() returns the indexes associated with a cache view. */ extern MagickExport IndexPacket *GetCacheViewIndexes(const ViewInfo *view) MAGICK_FUNC_PURE; /* GetCacheViewPixels() obtains a pixel region from a cache view for read/write access. */ extern MagickExport PixelPacket *GetCacheViewPixels(ViewInfo *view,const long x,const long y, const unsigned long columns,const unsigned long rows, ExceptionInfo *exception); /* Obtain the offset and size of the selected region. */ extern MagickExport RectangleInfo GetCacheViewRegion(const ViewInfo *view) MAGICK_FUNC_PURE; /* SetCacheViewPixels() gets blank writeable pixels from the pixel cache view. */ extern MagickExport PixelPacket *SetCacheViewPixels(ViewInfo *view,const long x,const long y, const unsigned long columns,const unsigned long rows, ExceptionInfo *exception); /* SyncCacheViewPixels() saves any changes to the pixel cache view. */ extern MagickExport MagickPassFail SyncCacheViewPixels(const ViewInfo *view,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) #include "magick/pixel_cache-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_CACHE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/pixel_iterator.h ================================================ /* Copyright (C) 2004-2016 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Interfaces to support simple iterative pixel read/update access within an image or between two images. These interfaces exist in order to eliminate large amounts of redundant code and to allow changing the underlying implementation without changing the using code. These interfaces intentionally omit any pixel position information in order to not constrain the implementation and to improve performance. User-provided callbacks must be thread-safe (preferably re-entrant) since they may be invoked by multiple threads. These interfaces have proven to be future safe (since implemented) and may be safely used by other applications/libraries. Written by Bob Friesenhahn, March 2004, Updated for regions 2008. */ #ifndef _PIXEL_ROW_ITERATOR_H #define _PIXEL_ROW_ITERATOR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Pixel iterator options. */ typedef struct _PixelIteratorOptions { int max_threads; /* Desired number of threads */ unsigned long signature; } PixelIteratorOptions; /* Initialize pixel iterator options with defaults. */ extern MagickExport void InitializePixelIteratorOptions(PixelIteratorOptions *options, ExceptionInfo *exception); /* Read-only access across pixel region. */ typedef MagickPassFail (*PixelIteratorMonoReadCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ const Image *const_image, /* Input image */ const PixelPacket *pixels, /* Pixel row */ const IndexPacket *indexes, /* Pixel indexes */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); extern MagickExport MagickPassFail PixelIterateMonoRead(PixelIteratorMonoReadCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const long x, const long y, const unsigned long columns, const unsigned long rows, const Image *image, ExceptionInfo *exception); typedef MagickPassFail (*PixelIteratorMonoModifyCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ Image *image, /* Modify image */ PixelPacket *pixels, /* Pixel row */ IndexPacket *indexes, /* Pixel row indexes */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); /* Write access across pixel region. */ extern MagickExport MagickPassFail PixelIterateMonoSet(PixelIteratorMonoModifyCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const long x, const long y, const unsigned long columns, const unsigned long rows, Image *image, ExceptionInfo *exception); /* Read-write access across pixel region. */ extern MagickExport MagickPassFail PixelIterateMonoModify(PixelIteratorMonoModifyCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const long x, const long y, const unsigned long columns, const unsigned long rows, Image *image, ExceptionInfo *exception); /* Read-only access across pixel regions of two images. */ typedef MagickPassFail (*PixelIteratorDualReadCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ const Image *first_image, /* First Input image */ const PixelPacket *first_pixels, /* Pixel row in first image */ const IndexPacket *first_indexes, /* Pixel row indexes in first image */ const Image *second_image, /* Second Input image */ const PixelPacket *second_pixels, /* Pixel row in second image */ const IndexPacket *second_indexes, /* Pixel row indexes in second image */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); extern MagickExport MagickPassFail PixelIterateDualRead(PixelIteratorDualReadCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *first_image, const long first_x, const long first_y, const Image *second_image, const long second_x, const long second_y, ExceptionInfo *exception); /* Read-write access across pixel regions of two images. The first (source) image is accessed read-only while the second (update) image is accessed as read-write. */ typedef MagickPassFail (*PixelIteratorDualModifyCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ const Image *source_image, /* Source image */ const PixelPacket *source_pixels, /* Pixel row in source image */ const IndexPacket *source_indexes, /* Pixel row indexes in source image */ Image *update_image, /* Update image */ PixelPacket *update_pixels, /* Pixel row in update image */ IndexPacket *update_indexes, /* Pixel row indexes in update image */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); extern MagickExport MagickPassFail PixelIterateDualModify(PixelIteratorDualModifyCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *source_image, const long source_x, const long source_y, Image *update_image, const long update_x, const long update_y, ExceptionInfo *exception); /* Read-write access across pixel regions of two images. The first (source) image is accessed read-only while the second (new) image is accessed for write (uninitialized pixels). */ typedef PixelIteratorDualModifyCallback PixelIteratorDualNewCallback; extern MagickExport MagickPassFail PixelIterateDualNew(PixelIteratorDualNewCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *source_image, const long source_x, const long source_y, Image *new_image, const long new_x, const long new_y, ExceptionInfo *exception); /* Read-read-write access across pixel regions of three images. The first two images are accessed read-only while the third is accessed as read-write. */ typedef MagickPassFail (*PixelIteratorTripleModifyCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ const Image *source1_image, /* Source 1 image */ const PixelPacket *source1_pixels, /* Pixel row in source 1 image */ const IndexPacket *source1_indexes, /* Pixel row indexes in source 1 image */ const Image *source2_image, /* Source 2 image */ const PixelPacket *source2_pixels, /* Pixel row in source 2 image */ const IndexPacket *source2_indexes, /* Pixel row indexes in source 2 image */ Image *update_image, /* Update image */ PixelPacket *update_pixels, /* Pixel row in update image */ IndexPacket *update_indexes, /* Pixel row indexes in update image */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); extern MagickExport MagickPassFail PixelIterateTripleModify(PixelIteratorTripleModifyCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *source1_image, const Image *source2_image, const long source_x, const long source_y, Image *update_image, const long update_x, const long update_y, ExceptionInfo *exception); /* Read-write access across pixel regions of two images. The first (source) image is accessed read-only while the second (new) image is accessed for write (uninitialized pixels). */ typedef PixelIteratorTripleModifyCallback PixelIteratorTripleNewCallback; extern MagickExport MagickPassFail PixelIterateTripleNew(PixelIteratorTripleNewCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *source1_image, const Image *source2_image, const long source_x, const long source_y, Image *new_image, const long new_x, const long new_y, ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _PIXEL_ROW_ITERATOR_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/plasma.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Plasma Methods. */ #ifndef _MAGICK_PLASMA_H #define _MAGICK_PLASMA_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" extern MagickExport MagickPassFail PlasmaImage(Image *image,const SegmentInfo *segment, unsigned long attenuate,unsigned long depth); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_PLASMA_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/profile.h ================================================ /* Copyright (C) 2004 - 2009 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Methods For Manipulating Embedded Image Profiles. */ #ifndef _MAGICK_PROFILE_H #define _MAGICK_PROFILE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Retrieve a profile from the image by name. */ extern MagickExport const unsigned char *GetImageProfile(const Image* image, const char *name, size_t *length); /* Remove a profile from the image by name. */ extern MagickExport MagickPassFail DeleteImageProfile(Image *image,const char *name); /* Apply (or add) a profile to the image. */ extern MagickExport MagickPassFail ProfileImage(Image *image,const char *name,unsigned char *profile, const size_t length,MagickBool clone); /* Add (or replace) profile to the image by name. */ extern MagickExport MagickPassFail SetImageProfile(Image *image,const char *name,const unsigned char *profile, const size_t length); /* Add (or append) profile to the image by name. */ extern MagickExport MagickPassFail AppendImageProfile(Image *image,const char *name, const unsigned char *profile_chunk, const size_t chunk_length); /* Generic iterator for traversing profiles. */ typedef void *ImageProfileIterator; /* Allocate an image profile iterator which points to one before the list so NextImageProfile() must be used to advance to first entry. */ extern MagickExport ImageProfileIterator AllocateImageProfileIterator(const Image *image); /* Advance to next image profile. Name, profile, and length are updated with information on current profile. MagickFail is returned when there are no more entries. */ extern MagickExport MagickPassFail NextImageProfile(ImageProfileIterator profile_iterator,const char **name, const unsigned char **profile,size_t *length); /* Deallocate profile iterator. */ extern MagickExport void DeallocateImageProfileIterator(ImageProfileIterator profile_iterator); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_PROFILE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/quantize.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Methods to Reduce the Number of Unique Colors in an Image. */ #ifndef _MAGICK_QUANTIZE_H #define _MAGICK_QUANTIZE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Define declarations. */ #define MaxTreeDepth 8 #define NodesInAList 1536 /* Typedef declarations. */ typedef struct _QuantizeInfo { unsigned long number_colors; unsigned int tree_depth, dither; ColorspaceType colorspace; unsigned int measure_error; unsigned long signature; } QuantizeInfo; /* Quantization utilities methods. */ extern MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *); extern MagickExport unsigned int GetImageQuantizeError(Image *), MapImage(Image *,const Image *,const unsigned int), MapImages(Image *,const Image *,const unsigned int), OrderedDitherImage(Image *), QuantizeImage(const QuantizeInfo *,Image *), QuantizeImages(const QuantizeInfo *,Image *), SegmentImage(Image *,const ColorspaceType,const unsigned int,const double, const double); extern MagickExport void CompressImageColormap(Image *), DestroyQuantizeInfo(QuantizeInfo *), GetQuantizeInfo(QuantizeInfo *), GrayscalePseudoClassImage(Image *,unsigned int); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/random.h ================================================ /* Copyright (C) 2009, 2014 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Random number generator (semi-public interfaces). Currently based on George Marsaglia's multiply-with-carry generator. This is a k=2 generator with a period >2^60. */ #ifndef _MAGICK_RANDOM_H #define _MAGICK_RANDOM_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ typedef struct _MagickRandomKernel { magick_uint32_t z; magick_uint32_t w; } MagickRandomKernel; #define MAGICK_RANDOM_MAX 4294967295 /* Generate a random integer value (0 - MAGICK_RANDOM_MAX) */ MagickExport magick_uint32_t MagickRandomInteger(void); /* Generate a random double value (0.0 - 1.0) */ MagickExport double MagickRandomReal(void); #if defined(MAGICK_IMPLEMENTATION) #include "magick/random-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* ifndef _MAGICK_RANDOM_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/registry.h ================================================ /* Copyright (C) 2003-2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Magick registry methods. */ #ifndef _MAGICK_REGISTRY_H #define _MAGICK_REGISTRY_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { UndefinedRegistryType, ImageRegistryType, ImageInfoRegistryType } RegistryType; /* Magick registry methods. */ extern MagickExport Image *GetImageFromMagickRegistry(const char *name,long *id, ExceptionInfo *exception); extern MagickExport long SetMagickRegistry(const RegistryType type,const void *blob, const size_t length,ExceptionInfo *exception); extern MagickExport MagickPassFail DeleteMagickRegistry(const long id); extern MagickExport void *GetMagickRegistry(const long id,RegistryType *type,size_t *length, ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) # include "magick/registry-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/render.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Drawing methods. */ #ifndef _MAGICK_RENDER_H #define _MAGICK_RENDER_H #include "magick/type.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { UndefinedAlign, LeftAlign, CenterAlign, RightAlign } AlignType; typedef enum { UserSpace, UserSpaceOnUse, ObjectBoundingBox } ClipPathUnits; typedef enum { NoDecoration, UnderlineDecoration, OverlineDecoration, LineThroughDecoration } DecorationType; typedef enum { UndefinedRule, #undef EvenOddRule EvenOddRule, NonZeroRule } FillRule; typedef enum { UndefinedGradient, LinearGradient, RadialGradient } GradientType; typedef enum { UndefinedCap, ButtCap, RoundCap, SquareCap } LineCap; typedef enum { UndefinedJoin, MiterJoin, RoundJoin, BevelJoin } LineJoin; typedef enum { PointMethod = 0, ReplaceMethod, FloodfillMethod, FillToBorderMethod, ResetMethod } PaintMethod; typedef enum { UndefinedPrimitive = 0, PointPrimitive, LinePrimitive, RectanglePrimitive, RoundRectanglePrimitive, ArcPrimitive, EllipsePrimitive, CirclePrimitive, PolylinePrimitive, PolygonPrimitive, BezierPrimitive, ColorPrimitive, MattePrimitive, TextPrimitive, ImagePrimitive, PathPrimitive } PrimitiveType; typedef enum { UndefinedReference, GradientReference } ReferenceType; typedef enum { UndefinedSpread, PadSpread, ReflectSpead, RepeatSpread } SpreadMethod; /* Typedef declarations. */ typedef struct _GradientInfo { GradientType type; PixelPacket color; SegmentInfo stop; unsigned long length; SpreadMethod spread; unsigned long signature; struct _GradientInfo *previous, *next; } GradientInfo; typedef struct _ElementReference { char *id; ReferenceType type; GradientInfo gradient; unsigned long signature; struct _ElementReference *previous, *next; } ElementReference; struct _DrawInfoExtra; /* forward decl.; see member "extra" below */ typedef struct _DrawInfo { char *primitive, *geometry; AffineMatrix affine; GravityType gravity; PixelPacket fill, stroke; double stroke_width; GradientInfo gradient; Image *fill_pattern, *tile, *stroke_pattern; unsigned int stroke_antialias, text_antialias; FillRule fill_rule; LineCap linecap; LineJoin linejoin; unsigned long miterlimit; double dash_offset; DecorationType decorate; CompositeOperator compose; char *text, *font, *family; StyleType style; StretchType stretch; unsigned long weight; char *encoding; double pointsize; char *density; AlignType align; PixelPacket undercolor, border_color; char *server_name; double *dash_pattern; /* Terminated by value 0.0 (i.e. < MagickEpsilon)*/ #if 0 char *clip_path; #endif /* Allow for expansion of DrawInfo without increasing its size. The internals are defined only in render.c. Clients outside of render.c can access the internals via the provided access functions (see below). This location in DrawInfo used to be occupied by char *clip_path. The clip_path member now lives in _DrawInfoExtra. */ struct _DrawInfoExtra *extra; SegmentInfo bounds; ClipPathUnits clip_units; Quantum opacity; unsigned int render, /* Bit fields in flags: Bit 0: should this DrawInfo should be drawn as: 0: normal (original behavior) 1: SVG compliant Bit 1: is the DrawInfo a clipping path: 0: is not a clipping path 1: is a clipping path Access to these bits should be through functions (defined in render.c): IsDrawInfoClippingPath() IsDrawInfoSVGCompliant() IsDrawInfoSVGCompliantClippingPath() SetDrawInfoClippingPath() SetDrawInfoSVGCompliant() At the present time the SVG compliance bit only affects how clipping paths are drawn. */ flags; /* previously "unused1" */ ElementReference element_reference; unsigned long signature; } DrawInfo; typedef struct _PointInfo { double x, y; } PointInfo; #if defined(MAGICK_IMPLEMENTATION) # include "magick/render-private.h" #endif /* if defined(MAGICK_IMPLEMENTATION) */ typedef struct _TypeMetric { PointInfo pixels_per_em; double ascent, descent, width, height, max_advance; SegmentInfo bounds; double underline_position, underline_thickness; } TypeMetric; /* Method declarations. */ extern MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *,const DrawInfo *); extern MagickExport MagickPassFail AnnotateImage(Image *,const DrawInfo *), DrawAffineImage(Image *,const Image *,const AffineMatrix *), DrawClipPath(Image *,const DrawInfo *,const char *), DrawImage(Image *,const DrawInfo *), DrawPatternPath(Image *,const DrawInfo *,const char *,Image **), GetTypeMetrics(Image *,const DrawInfo *,TypeMetric *); extern MagickExport void DestroyDrawInfo(DrawInfo *), GetDrawInfo(const ImageInfo *,DrawInfo *); /* provide public access to the clip_path member of DrawInfo */ extern MagickExport char **DrawInfoGetClipPath(const DrawInfo *) MAGICK_FUNC_PURE; /* provide public access to the composite_path member of DrawInfo */ extern MagickExport char **DrawInfoGetCompositePath(const DrawInfo *) MAGICK_FUNC_PURE; #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_RENDER_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/resize.h ================================================ /* Copyright (C) 2003 - 2012 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Resize Methods. */ #ifndef _MAGICK_RESIZE_H #define _MAGICK_RESIZE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ #define DefaultResizeFilter LanczosFilter #define DefaultThumbnailFilter BoxFilter extern MagickExport Image *MagnifyImage(const Image *,ExceptionInfo *), *MinifyImage(const Image *,ExceptionInfo *), *ResizeImage(const Image *,const unsigned long,const unsigned long, const FilterTypes,const double,ExceptionInfo *), *SampleImage(const Image *,const unsigned long,const unsigned long, ExceptionInfo *), *ScaleImage(const Image *,const unsigned long,const unsigned long, ExceptionInfo *), *ThumbnailImage(const Image *,const unsigned long,const unsigned long, ExceptionInfo *), *ZoomImage(const Image *,const unsigned long,const unsigned long, ExceptionInfo *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_RESIZE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/resource.h ================================================ /* Copyright (C) 2003 - 2015 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Resource methods. */ #ifndef _MAGICK_RESOURCE_H #define _MAGICK_RESOURCE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Typedef declarations. */ typedef enum { UndefinedResource=0, /* Undefined value */ DiskResource, /* Pixel cache total disk space (Gigabytes) */ FileResource, /* Pixel cache number of open files (Files) */ MapResource, /* Pixel cache total file memory-mapping (Megabytes) */ MemoryResource, /* Maximum pixel cache heap memory allocations (Megabytes) */ PixelsResource, /* Maximum number of pixels in single image (Pixels) */ ThreadsResource, /* Maximum number of worker threads */ WidthResource, /* Maximum pixel width of an image (Pixels) */ HeightResource /* Maximum pixel height of an image (Pixels) */ } ResourceType; /* Method declarations. */ extern MagickExport MagickPassFail AcquireMagickResource(const ResourceType type,const magick_uint64_t size), ListMagickResourceInfo(FILE *file,ExceptionInfo *exception), SetMagickResourceLimit(const ResourceType type,const magick_int64_t limit); extern MagickExport magick_int64_t GetMagickResource(const ResourceType type), GetMagickResourceLimit(const ResourceType type); extern MagickExport void DestroyMagickResources(void), InitializeMagickResources(void), LiberateMagickResource(const ResourceType type,const magick_uint64_t size); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/shear.h ================================================ /* Copyright (C) 2003-2012 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Shear Methods. */ #ifndef _MAGICK_SHEAR_H #define _MAGICK_SHEAR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *AffineTransformImage(const Image *,const AffineMatrix *,ExceptionInfo *), *AutoOrientImage(const Image *image,const OrientationType current_orientation, ExceptionInfo *exception), *RotateImage(const Image *,const double,ExceptionInfo *), *ShearImage(const Image *,const double,const double,ExceptionInfo *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_SHEAR_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/signature.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Digital signature methods. */ #ifndef _MAGICK_SIGNATURE_H #define _MAGICK_SIGNATURE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Define declarations. */ #define SignatureSize 64 /* Typedef declarations. */ typedef struct _SignatureInfo { unsigned long digest[8], low_order, high_order; long offset; unsigned char message[SignatureSize]; } SignatureInfo; /* Method declarations. */ extern MagickExport unsigned int SignatureImage(Image *); extern MagickExport void FinalizeSignature(SignatureInfo *), GetSignatureInfo(SignatureInfo *), TransformSignature(SignatureInfo *), UpdateSignature(SignatureInfo *,const unsigned char *,const size_t); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/statistics.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Statistics Methods. */ #ifndef _MAGICK_STATISTICS_H #define _MAGICK_STATISTICS_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" typedef struct _ImageChannelStatistics { /* Minimum value observed */ double maximum; /* Maximum value observed */ double minimum; /* Average (mean) value observed */ double mean; /* Standard deviation, sqrt(variance) */ double standard_deviation; /* Variance */ double variance; } ImageChannelStatistics; typedef struct _ImageStatistics { ImageChannelStatistics red; ImageChannelStatistics green; ImageChannelStatistics blue; ImageChannelStatistics opacity; } ImageStatistics; extern MagickExport MagickPassFail GetImageStatistics(const Image *image,ImageStatistics *statistics, ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_STATISTICS_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/symbols.h ================================================ /* Copyright (C) 2012-2018 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Library symbol name-scoping support. */ #if !defined(_MAGICK_SYMBOLS_H) #define _MAGICK_SYMBOLS_H #if defined(PREFIX_MAGICK_SYMBOLS) #define AccessCacheViewPixels GmAccessCacheViewPixels #define AccessDefaultCacheView GmAccessDefaultCacheView #define AccessDefinition GmAccessDefinition #define AccessImmutableIndexes GmAccessImmutableIndexes #define AccessMutableIndexes GmAccessMutableIndexes #define AccessMutablePixels GmAccessMutablePixels #define AccessThreadViewData GmAccessThreadViewData #define AccessThreadViewDataById GmAccessThreadViewDataById #define AcquireCacheView GmAcquireCacheView #define AcquireCacheViewIndexes GmAcquireCacheViewIndexes #define AcquireCacheViewPixels GmAcquireCacheViewPixels #define AcquireImagePixels GmAcquireImagePixels #define AcquireMagickRandomKernel GmAcquireMagickRandomKernel #define AcquireMagickResource GmAcquireMagickResource #define AcquireMemory GmAcquireMemory #define AcquireOneCacheViewPixel GmAcquireOneCacheViewPixel #define AcquireOnePixel GmAcquireOnePixel #define AcquireOnePixelByReference GmAcquireOnePixelByReference #define AcquireSemaphoreInfo GmAcquireSemaphoreInfo #define AcquireString GmAcquireString #define AcquireTemporaryFileDescriptor GmAcquireTemporaryFileDescriptor #define AcquireTemporaryFileName GmAcquireTemporaryFileName #define AcquireTemporaryFileStream GmAcquireTemporaryFileStream #define AdaptiveThresholdImage GmAdaptiveThresholdImage #define AddDefinition GmAddDefinition #define AddDefinitions GmAddDefinitions #define AddNoiseImage GmAddNoiseImage #define AddNoiseImageChannel GmAddNoiseImageChannel #define AffineTransformImage GmAffineTransformImage #define AllocateImage GmAllocateImage #define AllocateImageColormap GmAllocateImageColormap #define AllocateImageProfileIterator GmAllocateImageProfileIterator #define AllocateNextImage GmAllocateNextImage #define AllocateSemaphoreInfo GmAllocateSemaphoreInfo #define AllocateString GmAllocateString #define AllocateThreadViewDataArray GmAllocateThreadViewDataArray #define AllocateThreadViewDataSet GmAllocateThreadViewDataSet #define AllocateThreadViewSet GmAllocateThreadViewSet #define AnalyzeImage GmAnalyzeImage #define AnimateImageCommand GmAnimateImageCommand #define AnimateImages GmAnimateImages #define AnnotateImage GmAnnotateImage #define AppendImageFormat GmAppendImageFormat #define AppendImageProfile GmAppendImageProfile #define AppendImageToList GmAppendImageToList #define AppendImages GmAppendImages #define Ascii85Encode GmAscii85Encode #define Ascii85Flush GmAscii85Flush #define Ascii85Initialize GmAscii85Initialize #define Ascii85WriteByteHook GmAscii85WriteByteHook #define AssignThreadViewData GmAssignThreadViewData #define AttachBlob GmAttachBlob #define AutoOrientImage GmAutoOrientImage #define AverageImages GmAverageImages #define Base64Decode GmBase64Decode #define Base64Encode GmBase64Encode #define BenchmarkImageCommand GmBenchmarkImageCommand #define BlackThresholdImage GmBlackThresholdImage #define BlobIsSeekable GmBlobIsSeekable #define BlobModeToString GmBlobModeToString #define BlobReserveSize GmBlobReserveSize #define BlobToFile GmBlobToFile #define BlobToImage GmBlobToImage #define BlobWriteByteHook GmBlobWriteByteHook #define BlurImage GmBlurImage #define BlurImageChannel GmBlurImageChannel #define BorderImage GmBorderImage #define CatchException GmCatchException #define CatchImageException GmCatchImageException #define CdlImage GmCdlImage #define ChannelImage GmChannelImage #define ChannelThresholdImage GmChannelThresholdImage #define ChannelTypeToString GmChannelTypeToString #define CharcoalImage GmCharcoalImage #define CheckImagePixelLimits GmCheckImagePixelLimits #define ChopImage GmChopImage #define ClassTypeToString GmClassTypeToString #define ClipImage GmClipImage #define ClipPathImage GmClipPathImage #define CloneBlobInfo GmCloneBlobInfo #define CloneDrawInfo GmCloneDrawInfo #define CloneImage GmCloneImage #define CloneImageAttributes GmCloneImageAttributes #define CloneImageInfo GmCloneImageInfo #define CloneImageList GmCloneImageList #define CloneMemory GmCloneMemory #define CloneMontageInfo GmCloneMontageInfo #define CloneQuantizeInfo GmCloneQuantizeInfo #define CloneString GmCloneString #define CloseBlob GmCloseBlob #define CloseCacheView GmCloseCacheView #define CoalesceImages GmCoalesceImages #define ColorFloodfillImage GmColorFloodfillImage #define ColorMatrixImage GmColorMatrixImage #define ColorizeImage GmColorizeImage #define ColorspaceTypeToString GmColorspaceTypeToString #define CompareImageCommand GmCompareImageCommand #define CompositeImage GmCompositeImage #define CompositeImageCommand GmCompositeImageCommand #define CompositeImageRegion GmCompositeImageRegion #define CompositeMaskImage GmCompositeMaskImage #define CompositeOperatorToString GmCompositeOperatorToString #define CompositePathImage GmCompositePathImage #define CompressImageColormap GmCompressImageColormap #define CompressionTypeToString GmCompressionTypeToString #define ConcatenateString GmConcatenateString #define ConfirmAccessModeToString GmConfirmAccessModeToString #define ConjureImageCommand GmConjureImageCommand #define ConstituteImage GmConstituteImage #define ConstituteTextureImage GmConstituteTextureImage #define ContinueTimer GmContinueTimer #define Contrast GmContrast #define ContrastImage GmContrastImage #define ConvertImageCommand GmConvertImageCommand #define ConvolveImage GmConvolveImage #define CopyException GmCopyException #define CropImage GmCropImage #define CycleColormapImage GmCycleColormapImage #define DeallocateImageProfileIterator GmDeallocateImageProfileIterator #define DeconstructImages GmDeconstructImages #define DefineClientName GmDefineClientName #define DefineClientPathAndName GmDefineClientPathAndName #define DeleteImageFromList GmDeleteImageFromList #define DeleteImageProfile GmDeleteImageProfile #define DeleteMagickRegistry GmDeleteMagickRegistry #define DescribeImage GmDescribeImage #define DespeckleImage GmDespeckleImage #define DestroyBlob GmDestroyBlob #define DestroyBlobInfo GmDestroyBlobInfo #define DestroyCacheInfo GmDestroyCacheInfo #define DestroyColorInfo GmDestroyColorInfo #define DestroyConstitute GmDestroyConstitute #define DestroyDelegateInfo GmDestroyDelegateInfo #define DestroyDrawInfo GmDestroyDrawInfo #define DestroyExceptionInfo GmDestroyExceptionInfo #define DestroyImage GmDestroyImage #define DestroyImageAttributes GmDestroyImageAttributes #define DestroyImageInfo GmDestroyImageInfo #define DestroyImageList GmDestroyImageList #define DestroyImagePixels GmDestroyImagePixels #define DestroyLogInfo GmDestroyLogInfo #define DestroyMagicInfo GmDestroyMagicInfo #define DestroyMagick GmDestroyMagick #define DestroyMagickExceptionHandling GmDestroyMagickExceptionHandling #define DestroyMagickModules GmDestroyMagickModules #define DestroyMagickMonitor GmDestroyMagickMonitor #define DestroyMagickRandomGenerator GmDestroyMagickRandomGenerator #define DestroyMagickRegistry GmDestroyMagickRegistry #define DestroyMagickResources GmDestroyMagickResources #define DestroyMontageInfo GmDestroyMontageInfo #define DestroyQuantizeInfo GmDestroyQuantizeInfo #define DestroySemaphore GmDestroySemaphore #define DestroySemaphoreInfo GmDestroySemaphoreInfo #define DestroyTemporaryFiles GmDestroyTemporaryFiles #define DestroyThreadViewDataSet GmDestroyThreadViewDataSet #define DestroyThreadViewSet GmDestroyThreadViewSet #define DestroyTypeInfo GmDestroyTypeInfo #define DetachBlob GmDetachBlob #define DifferenceImage GmDifferenceImage #define DisassociateBlob GmDisassociateBlob #define DispatchImage GmDispatchImage #define DisplayImageCommand GmDisplayImageCommand #define DisplayImages GmDisplayImages #define DrawAffine GmDrawAffine #define DrawAffineImage GmDrawAffineImage #define DrawAllocateContext GmDrawAllocateContext #define DrawAnnotation GmDrawAnnotation #define DrawArc GmDrawArc #define DrawBezier GmDrawBezier #define DrawCircle GmDrawCircle #define DrawClipPath GmDrawClipPath #define DrawColor GmDrawColor #define DrawComment GmDrawComment #define DrawComposite GmDrawComposite #define DrawCompositeMask GmDrawCompositeMask #define DrawDestroyContext GmDrawDestroyContext #define DrawEllipse GmDrawEllipse #define DrawGetClipPath GmDrawGetClipPath #define DrawGetClipRule GmDrawGetClipRule #define DrawGetClipUnits GmDrawGetClipUnits #define DrawGetFillColor GmDrawGetFillColor #define DrawGetFillOpacity GmDrawGetFillOpacity #define DrawGetFillRule GmDrawGetFillRule #define DrawGetFont GmDrawGetFont #define DrawGetFontFamily GmDrawGetFontFamily #define DrawGetFontSize GmDrawGetFontSize #define DrawGetFontStretch GmDrawGetFontStretch #define DrawGetFontStyle GmDrawGetFontStyle #define DrawGetFontWeight GmDrawGetFontWeight #define DrawGetGravity GmDrawGetGravity #define DrawGetStrokeAntialias GmDrawGetStrokeAntialias #define DrawGetStrokeColor GmDrawGetStrokeColor #define DrawGetStrokeDashArray GmDrawGetStrokeDashArray #define DrawGetStrokeDashOffset GmDrawGetStrokeDashOffset #define DrawGetStrokeLineCap GmDrawGetStrokeLineCap #define DrawGetStrokeLineJoin GmDrawGetStrokeLineJoin #define DrawGetStrokeMiterLimit GmDrawGetStrokeMiterLimit #define DrawGetStrokeOpacity GmDrawGetStrokeOpacity #define DrawGetStrokeWidth GmDrawGetStrokeWidth #define DrawGetTextAntialias GmDrawGetTextAntialias #define DrawGetTextDecoration GmDrawGetTextDecoration #define DrawGetTextEncoding GmDrawGetTextEncoding #define DrawGetTextUnderColor GmDrawGetTextUnderColor #define DrawImage GmDrawImage #define DrawInfoGetClipPath GmDrawInfoGetClipPath #define DrawInfoGetCompositePath GmDrawInfoGetCompositePath #define DrawLine GmDrawLine #define DrawMatte GmDrawMatte #define DrawPathClose GmDrawPathClose #define DrawPathCurveToAbsolute GmDrawPathCurveToAbsolute #define DrawPathCurveToQuadraticBezierAbsolute GmDrawPathCurveToQuadraticBezierAbsolute #define DrawPathCurveToQuadraticBezierRelative GmDrawPathCurveToQuadraticBezierRelative #define DrawPathCurveToQuadraticBezierSmoothAbsolute GmDrawPathCurveToQuadraticBezierSmoothAbsolute #define DrawPathCurveToQuadraticBezierSmoothRelative GmDrawPathCurveToQuadraticBezierSmoothRelative #define DrawPathCurveToRelative GmDrawPathCurveToRelative #define DrawPathCurveToSmoothAbsolute GmDrawPathCurveToSmoothAbsolute #define DrawPathCurveToSmoothRelative GmDrawPathCurveToSmoothRelative #define DrawPathEllipticArcAbsolute GmDrawPathEllipticArcAbsolute #define DrawPathEllipticArcRelative GmDrawPathEllipticArcRelative #define DrawPathFinish GmDrawPathFinish #define DrawPathLineToAbsolute GmDrawPathLineToAbsolute #define DrawPathLineToHorizontalAbsolute GmDrawPathLineToHorizontalAbsolute #define DrawPathLineToHorizontalRelative GmDrawPathLineToHorizontalRelative #define DrawPathLineToRelative GmDrawPathLineToRelative #define DrawPathLineToVerticalAbsolute GmDrawPathLineToVerticalAbsolute #define DrawPathLineToVerticalRelative GmDrawPathLineToVerticalRelative #define DrawPathMoveToAbsolute GmDrawPathMoveToAbsolute #define DrawPathMoveToRelative GmDrawPathMoveToRelative #define DrawPathStart GmDrawPathStart #define DrawPatternPath GmDrawPatternPath #define DrawPeekGraphicContext GmDrawPeekGraphicContext #define DrawPoint GmDrawPoint #define DrawPolygon GmDrawPolygon #define DrawPolyline GmDrawPolyline #define DrawPopClipPath GmDrawPopClipPath #define DrawPopDefs GmDrawPopDefs #define DrawPopGraphicContext GmDrawPopGraphicContext #define DrawPopPattern GmDrawPopPattern #define DrawPushClipPath GmDrawPushClipPath #define DrawPushDefs GmDrawPushDefs #define DrawPushGraphicContext GmDrawPushGraphicContext #define DrawPushPattern GmDrawPushPattern #define DrawRectangle GmDrawRectangle #define DrawRender GmDrawRender #define DrawRotate GmDrawRotate #define DrawRoundRectangle GmDrawRoundRectangle #define DrawScale GmDrawScale #define DrawSetClipPath GmDrawSetClipPath #define DrawSetClipRule GmDrawSetClipRule #define DrawSetClipUnits GmDrawSetClipUnits #define DrawSetFillColor GmDrawSetFillColor #define DrawSetFillColorString GmDrawSetFillColorString #define DrawSetFillOpacity GmDrawSetFillOpacity #define DrawSetFillPatternURL GmDrawSetFillPatternURL #define DrawSetFillRule GmDrawSetFillRule #define DrawSetFont GmDrawSetFont #define DrawSetFontFamily GmDrawSetFontFamily #define DrawSetFontSize GmDrawSetFontSize #define DrawSetFontStretch GmDrawSetFontStretch #define DrawSetFontStyle GmDrawSetFontStyle #define DrawSetFontWeight GmDrawSetFontWeight #define DrawSetGravity GmDrawSetGravity #define DrawSetStrokeAntialias GmDrawSetStrokeAntialias #define DrawSetStrokeColor GmDrawSetStrokeColor #define DrawSetStrokeColorString GmDrawSetStrokeColorString #define DrawSetStrokeDashArray GmDrawSetStrokeDashArray #define DrawSetStrokeDashOffset GmDrawSetStrokeDashOffset #define DrawSetStrokeLineCap GmDrawSetStrokeLineCap #define DrawSetStrokeLineJoin GmDrawSetStrokeLineJoin #define DrawSetStrokeMiterLimit GmDrawSetStrokeMiterLimit #define DrawSetStrokeOpacity GmDrawSetStrokeOpacity #define DrawSetStrokePatternURL GmDrawSetStrokePatternURL #define DrawSetStrokeWidth GmDrawSetStrokeWidth #define DrawSetTextAntialias GmDrawSetTextAntialias #define DrawSetTextDecoration GmDrawSetTextDecoration #define DrawSetTextEncoding GmDrawSetTextEncoding #define DrawSetTextUnderColor GmDrawSetTextUnderColor #define DrawSetTextUnderColorString GmDrawSetTextUnderColorString #define DrawSetViewbox GmDrawSetViewbox #define DrawSkewX GmDrawSkewX #define DrawSkewY GmDrawSkewY #define DrawTranslate GmDrawTranslate #define EOFBlob GmEOFBlob #define EdgeImage GmEdgeImage #define EmbossImage GmEmbossImage #define EndianTypeToString GmEndianTypeToString #define EnhanceImage GmEnhanceImage #define EqualizeImage GmEqualizeImage #define EscapeString GmEscapeString #define ExecuteModuleProcess GmExecuteModuleProcess #define ExpandAffine GmExpandAffine #define ExpandFilename GmExpandFilename #define ExpandFilenames GmExpandFilenames #define ExportImageChannel GmExportImageChannel #define ExportImagePixelArea GmExportImagePixelArea #define ExportPixelAreaOptionsInit GmExportPixelAreaOptionsInit #define ExportViewPixelArea GmExportViewPixelArea #define ExtentImage GmExtentImage #define FileToBlob GmFileToBlob #define FinalizeSignature GmFinalizeSignature #define FlattenImages GmFlattenImages #define FlipImage GmFlipImage #define FlopImage GmFlopImage #define FormatSize GmFormatSize #define FormatString GmFormatString #define FormatStringList GmFormatStringList #define FrameImage GmFrameImage #define FuzzyColorMatch GmFuzzyColorMatch #define GammaImage GmGammaImage #define GaussianBlurImage GmGaussianBlurImage #define GaussianBlurImageChannel GmGaussianBlurImageChannel #define GenerateDifferentialNoise GmGenerateDifferentialNoise #define GenerateNoise GmGenerateNoise #define GetBlobFileHandle GmGetBlobFileHandle #define GetBlobFirstErrno GmGetBlobFirstErrno #define GetBlobInfo GmGetBlobInfo #define GetBlobIsOpen GmGetBlobIsOpen #define GetBlobSize GmGetBlobSize #define GetBlobStatus GmGetBlobStatus #define GetBlobStreamData GmGetBlobStreamData #define GetBlobTemporary GmGetBlobTemporary #define GetCacheInfo GmGetCacheInfo #define GetCacheView GmGetCacheView #define GetCacheViewArea GmGetCacheViewArea #define GetCacheViewImage GmGetCacheViewImage #define GetCacheViewIndexes GmGetCacheViewIndexes #define GetCacheViewPixels GmGetCacheViewPixels #define GetCacheViewRegion GmGetCacheViewRegion #define GetClientFilename GmGetClientFilename #define GetClientName GmGetClientName #define GetClientPath GmGetClientPath #define GetColorHistogram GmGetColorHistogram #define GetColorInfo GmGetColorInfo #define GetColorInfoArray GmGetColorInfoArray #define GetColorList GmGetColorList #define GetColorTuple GmGetColorTuple #define GetConfigureBlob GmGetConfigureBlob #define GetDelegateCommand GmGetDelegateCommand #define GetDelegateInfo GmGetDelegateInfo #define GetDrawInfo GmGetDrawInfo #define GetElapsedTime GmGetElapsedTime #define GetExceptionInfo GmGetExceptionInfo #define GetExecutionPath GmGetExecutionPath #define GetExecutionPathUsingName GmGetExecutionPathUsingName #define GetFirstImageInList GmGetFirstImageInList #define GetGeometry GmGetGeometry #define GetImageAttribute GmGetImageAttribute #define GetImageBoundingBox GmGetImageBoundingBox #define GetImageChannelDepth GmGetImageChannelDepth #define GetImageChannelDifference GmGetImageChannelDifference #define GetImageChannelDistortion GmGetImageChannelDistortion #define GetImageCharacteristics GmGetImageCharacteristics #define GetImageClipMask GmGetImageClipMask #define GetImageClippingPathAttribute GmGetImageClippingPathAttribute #define GetImageCompositeMask GmGetImageCompositeMask #define GetImageDepth GmGetImageDepth #define GetImageDistortion GmGetImageDistortion #define GetImageException GmGetImageException #define GetImageFromList GmGetImageFromList #define GetImageFromMagickRegistry GmGetImageFromMagickRegistry #define GetImageGeometry GmGetImageGeometry #define GetImageIndexInList GmGetImageIndexInList #define GetImageInfo GmGetImageInfo #define GetImageInfoAttribute GmGetImageInfoAttribute #define GetImageListLength GmGetImageListLength #define GetImageMagick GmGetImageMagick #define GetImagePixels GmGetImagePixels #define GetImagePixelsEx GmGetImagePixelsEx #define GetImageProfile GmGetImageProfile #define GetImageQuantizeError GmGetImageQuantizeError #define GetImageStatistics GmGetImageStatistics #define GetImageType GmGetImageType #define GetImageVirtualPixelMethod GmGetImageVirtualPixelMethod #define GetIndexes GmGetIndexes #define GetLastImageInList GmGetLastImageInList #define GetLocaleExceptionMessage GmGetLocaleExceptionMessage #define GetLocaleMessage GmGetLocaleMessage #define GetLocaleMessageFromID GmGetLocaleMessageFromID #define GetMagickCopyright GmGetMagickCopyright #define GetMagickDimension GmGetMagickDimension #define GetMagickFileFormat GmGetMagickFileFormat #define GetMagickGeometry GmGetMagickGeometry #define GetMagickInfo GmGetMagickInfo #define GetMagickInfoArray GmGetMagickInfoArray #define GetMagickRegistry GmGetMagickRegistry #define GetMagickResource GmGetMagickResource #define GetMagickResourceLimit GmGetMagickResourceLimit #define GetMagickVersion GmGetMagickVersion #define GetMagickWebSite GmGetMagickWebSite #define GetMontageInfo GmGetMontageInfo #define GetNextImageInList GmGetNextImageInList #define GetNumberColors GmGetNumberColors #define GetOnePixel GmGetOnePixel #define GetOptimalKernelWidth GmGetOptimalKernelWidth #define GetOptimalKernelWidth1D GmGetOptimalKernelWidth1D #define GetOptimalKernelWidth2D GmGetOptimalKernelWidth2D #define GetPageGeometry GmGetPageGeometry #define GetPathComponent GmGetPathComponent #define GetPixelCacheArea GmGetPixelCacheArea #define GetPixelCacheInCore GmGetPixelCacheInCore #define GetPixelCachePresent GmGetPixelCachePresent #define GetPixels GmGetPixels #define GetPostscriptDelegateInfo GmGetPostscriptDelegateInfo #define GetPreviousImageInList GmGetPreviousImageInList #define GetQuantizeInfo GmGetQuantizeInfo #define GetSignatureInfo GmGetSignatureInfo #define GetThreadViewDataSetAllocatedViews GmGetThreadViewDataSetAllocatedViews #define GetTimerInfo GmGetTimerInfo #define GetTimerResolution GmGetTimerResolution #define GetToken GmGetToken #define GetTypeInfo GmGetTypeInfo #define GetTypeInfoByFamily GmGetTypeInfoByFamily #define GetTypeList GmGetTypeList #define GetTypeMetrics GmGetTypeMetrics #define GetUserTime GmGetUserTime #define GlobExpression GmGlobExpression #define GradientImage GmGradientImage #define GravityTypeToString GmGravityTypeToString #define GrayscalePseudoClassImage GmGrayscalePseudoClassImage #define HSLTransform GmHSLTransform #define HWBTransform GmHWBTransform #define HaldClutImage GmHaldClutImage #define HighlightStyleToString GmHighlightStyleToString #define HuffmanDecodeImage GmHuffmanDecodeImage #define HuffmanEncode2Image GmHuffmanEncode2Image #define HuffmanEncodeImage GmHuffmanEncodeImage #define Hull GmHull #define IdentifyImageCommand GmIdentifyImageCommand #define IdentityAffine GmIdentityAffine #define ImageGetClipMask GmImageGetClipMask #define ImageGetCompositeMask GmImageGetCompositeMask #define ImageListToArray GmImageListToArray #define ImageToBlob GmImageToBlob #define ImageToFile GmImageToFile #define ImageToHuffman2DBlob GmImageToHuffman2DBlob #define ImageToJPEGBlob GmImageToJPEGBlob #define ImageTypeToString GmImageTypeToString #define ImplodeImage GmImplodeImage #define ImportImageChannel GmImportImageChannel #define ImportImageChannelsMasked GmImportImageChannelsMasked #define ImportImageCommand GmImportImageCommand #define ImportImagePixelArea GmImportImagePixelArea #define ImportPixelAreaOptionsInit GmImportPixelAreaOptionsInit #define ImportViewPixelArea GmImportViewPixelArea #define InitializeColorInfo GmInitializeColorInfo #define InitializeConstitute GmInitializeConstitute #define InitializeDelegateInfo GmInitializeDelegateInfo #define InitializeDifferenceImageOptions GmInitializeDifferenceImageOptions #define InitializeDifferenceStatistics GmInitializeDifferenceStatistics #define InitializeLogInfo GmInitializeLogInfo #define InitializeLogInfoPost GmInitializeLogInfoPost #define InitializeMagicInfo GmInitializeMagicInfo #define InitializeMagick GmInitializeMagick #define InitializeMagickEx GmInitializeMagickEx #define InitializeMagickExceptionHandling GmInitializeMagickExceptionHandling #define InitializeMagickModules GmInitializeMagickModules #define InitializeMagickMonitor GmInitializeMagickMonitor #define InitializeMagickRandomGenerator GmInitializeMagickRandomGenerator #define InitializeMagickRandomKernel GmInitializeMagickRandomKernel #define InitializeMagickRegistry GmInitializeMagickRegistry #define InitializeMagickResources GmInitializeMagickResources #define InitializePixelIteratorOptions GmInitializePixelIteratorOptions #define InitializeSemaphore GmInitializeSemaphore #define InitializeTemporaryFiles GmInitializeTemporaryFiles #define InitializeTypeInfo GmInitializeTypeInfo #define InsertImageInList GmInsertImageInList #define InsertRowHDU GmInsertRowHDU #define InterlaceTypeToString GmInterlaceTypeToString #define InterpolateColor GmInterpolateColor #define InterpolateViewColor GmInterpolateViewColor #define InvokeDelegate GmInvokeDelegate #define InvokePostscriptDelegate GmInvokePostscriptDelegate #define IsAccessible GmIsAccessible #define IsAccessibleAndNotEmpty GmIsAccessibleAndNotEmpty #define IsAccessibleNoLogging GmIsAccessibleNoLogging #define IsEventLogging GmIsEventLogging #define IsGeometry GmIsGeometry #define IsGlob GmIsGlob #define IsGrayImage GmIsGrayImage #define IsImagesEqual GmIsImagesEqual #define IsMagickConflict GmIsMagickConflict #define IsMonochromeImage GmIsMonochromeImage #define IsOpaqueImage GmIsOpaqueImage #define IsPaletteImage GmIsPaletteImage #define IsSubimage GmIsSubimage #define IsTaintImage GmIsTaintImage #define IsWriteable GmIsWriteable #define LZWEncode2Image GmLZWEncode2Image #define LZWEncodeImage GmLZWEncodeImage #define LevelImage GmLevelImage #define LevelImageChannel GmLevelImageChannel #define LiberateMagickResource GmLiberateMagickResource #define LiberateMemory GmLiberateMemory #define LiberateSemaphoreInfo GmLiberateSemaphoreInfo #define LiberateTemporaryFile GmLiberateTemporaryFile #define ListColorInfo GmListColorInfo #define ListDelegateInfo GmListDelegateInfo #define ListFiles GmListFiles #define ListMagicInfo GmListMagicInfo #define ListMagickInfo GmListMagickInfo #define ListMagickResourceInfo GmListMagickResourceInfo #define ListModuleMap GmListModuleMap #define ListTypeInfo GmListTypeInfo #define LocaleCompare GmLocaleCompare #define LocaleLower GmLocaleLower #define LocaleNCompare GmLocaleNCompare #define LocaleUpper GmLocaleUpper #define LockSemaphoreInfo GmLockSemaphoreInfo #define MSBOrderLong GmMSBOrderLong #define MSBOrderShort GmMSBOrderShort #define MagickAllocFunctions GmMagickAllocFunctions #define MagickArraySize GmMagickArraySize #define MagickAtoFChk GmMagickAtoFChk #define MagickAtoIChk GmMagickAtoIChk #define MagickAtoLChk GmMagickAtoLChk #define MagickAtoUIChk GmMagickAtoUIChk #define MagickAtoULChk GmMagickAtoULChk #define MagickBitStreamInitializeRead GmMagickBitStreamInitializeRead #define MagickBitStreamInitializeWrite GmMagickBitStreamInitializeWrite #define MagickBitStreamMSBRead GmMagickBitStreamMSBRead #define MagickBitStreamMSBWrite GmMagickBitStreamMSBWrite #define MagickCloneMemory GmMagickCloneMemory #define MagickCommand GmMagickCommand #define MagickCompositeImageUnderColor GmMagickCompositeImageUnderColor #define MagickConfirmAccess GmMagickConfirmAccess #define MagickConstrainColormapIndex GmMagickConstrainColormapIndex #define MagickCreateDirectoryPath GmMagickCreateDirectoryPath #define MagickDestroyCommandInfo GmMagickDestroyCommandInfo #define MagickFindRawImageMinMax GmMagickFindRawImageMinMax #define MagickFmax GmMagickFmax #define MagickFmin GmMagickFmin #define MagickFormatString GmMagickFormatString #define MagickFormatStringList GmMagickFormatStringList #define MagickFree GmMagickFree #define MagickFreeAligned GmMagickFreeAligned #define MagickGetBitRevTable GmMagickGetBitRevTable #define MagickGetFileAttributes GmMagickGetFileAttributes #define MagickGetFileSystemBlockSize GmMagickGetFileSystemBlockSize #define MagickGetMMUPageSize GmMagickGetMMUPageSize #define MagickGetQuantumSamplesPerPixel GmMagickGetQuantumSamplesPerPixel #define MagickGetToken GmMagickGetToken #define MagickInitializeCommandInfo GmMagickInitializeCommandInfo #define MagickIsTrue GmMagickIsTrue #define MagickMalloc GmMagickMalloc #define MagickMallocAligned GmMagickMallocAligned #define MagickMallocAlignedArray GmMagickMallocAlignedArray #define MagickMallocArray GmMagickMallocArray #define MagickMallocCleared GmMagickMallocCleared #define MagickMapAccessEntry GmMagickMapAccessEntry #define MagickMapAddEntry GmMagickMapAddEntry #define MagickMapAllocateIterator GmMagickMapAllocateIterator #define MagickMapAllocateMap GmMagickMapAllocateMap #define MagickMapClearMap GmMagickMapClearMap #define MagickMapCloneMap GmMagickMapCloneMap #define MagickMapCopyBlob GmMagickMapCopyBlob #define MagickMapCopyString GmMagickMapCopyString #define MagickMapDeallocateBlob GmMagickMapDeallocateBlob #define MagickMapDeallocateIterator GmMagickMapDeallocateIterator #define MagickMapDeallocateMap GmMagickMapDeallocateMap #define MagickMapDeallocateString GmMagickMapDeallocateString #define MagickMapDereferenceIterator GmMagickMapDereferenceIterator #define MagickMapIterateNext GmMagickMapIterateNext #define MagickMapIteratePrevious GmMagickMapIteratePrevious #define MagickMapIterateToBack GmMagickMapIterateToBack #define MagickMapIterateToFront GmMagickMapIterateToFront #define MagickMapRemoveEntry GmMagickMapRemoveEntry #define MagickMonitor GmMagickMonitor #define MagickMonitorActive GmMagickMonitorActive #define MagickMonitorFormatted GmMagickMonitorFormatted #define MagickRandNewSeed GmMagickRandNewSeed #define MagickRandReentrant GmMagickRandReentrant #define MagickRandomInteger GmMagickRandomInteger #define MagickRandomReal GmMagickRandomReal #define MagickRealloc GmMagickRealloc #define MagickReverseBits GmMagickReverseBits #define MagickSceneFileName GmMagickSceneFileName #define MagickSetConfirmAccessHandler GmMagickSetConfirmAccessHandler #define MagickSetFileAttributes GmMagickSetFileAttributes #define MagickSetFileSystemBlockSize GmMagickSetFileSystemBlockSize #define MagickSizeStrToInt64 GmMagickSizeStrToInt64 #define MagickSpawnVP GmMagickSpawnVP #define MagickStripSpacesFromString GmMagickStripSpacesFromString #define MagickStrlCat GmMagickStrlCat #define MagickStrlCpy GmMagickStrlCpy #define MagickStrlCpyTrunc GmMagickStrlCpyTrunc #define MagickSwabArrayOfDouble GmMagickSwabArrayOfDouble #define MagickSwabArrayOfFloat GmMagickSwabArrayOfFloat #define MagickSwabArrayOfUInt16 GmMagickSwabArrayOfUInt16 #define MagickSwabArrayOfUInt32 GmMagickSwabArrayOfUInt32 #define MagickSwabDouble GmMagickSwabDouble #define MagickSwabFloat GmMagickSwabFloat #define MagickSwabUInt16 GmMagickSwabUInt16 #define MagickSwabUInt32 GmMagickSwabUInt32 #define MagickToMime GmMagickToMime #define MagickTsdGetSpecific GmMagickTsdGetSpecific #define MagickTsdKeyCreate GmMagickTsdKeyCreate #define MagickTsdKeyCreate2 GmMagickTsdKeyCreate2 #define MagickTsdKeyDelete GmMagickTsdKeyDelete #define MagickTsdSetSpecific GmMagickTsdSetSpecific #define MagickWordStreamInitializeRead GmMagickWordStreamInitializeRead #define MagickWordStreamInitializeWrite GmMagickWordStreamInitializeWrite #define MagickWordStreamLSBRead GmMagickWordStreamLSBRead #define MagickWordStreamLSBWrite GmMagickWordStreamLSBWrite #define MagickWordStreamLSBWriteFlush GmMagickWordStreamLSBWriteFlush #define MagickXAnimateBackgroundImage GmMagickXAnimateBackgroundImage #define MagickXAnimateImages GmMagickXAnimateImages #define MagickXAnnotateImage GmMagickXAnnotateImage #define MagickXBestFont GmMagickXBestFont #define MagickXBestIconSize GmMagickXBestIconSize #define MagickXBestPixel GmMagickXBestPixel #define MagickXBestVisualInfo GmMagickXBestVisualInfo #define MagickXCheckRefreshWindows GmMagickXCheckRefreshWindows #define MagickXClientMessage GmMagickXClientMessage #define MagickXColorBrowserWidget GmMagickXColorBrowserWidget #define MagickXCommandWidget GmMagickXCommandWidget #define MagickXConfigureImageColormap GmMagickXConfigureImageColormap #define MagickXConfirmWidget GmMagickXConfirmWidget #define MagickXConstrainWindowPosition GmMagickXConstrainWindowPosition #define MagickXDelay GmMagickXDelay #define MagickXDestroyResourceInfo GmMagickXDestroyResourceInfo #define MagickXDestroyWindowColors GmMagickXDestroyWindowColors #define MagickXDestroyX11Resources GmMagickXDestroyX11Resources #define MagickXDestroyXWindowInfo GmMagickXDestroyXWindowInfo #define MagickXDestroyXWindows GmMagickXDestroyXWindows #define MagickXDialogWidget GmMagickXDialogWidget #define MagickXDisplayBackgroundImage GmMagickXDisplayBackgroundImage #define MagickXDisplayImage GmMagickXDisplayImage #define MagickXDisplayImageInfo GmMagickXDisplayImageInfo #define MagickXDrawImage GmMagickXDrawImage #define MagickXError GmMagickXError #define MagickXFileBrowserWidget GmMagickXFileBrowserWidget #define MagickXFontBrowserWidget GmMagickXFontBrowserWidget #define MagickXFreeResources GmMagickXFreeResources #define MagickXFreeStandardColormap GmMagickXFreeStandardColormap #define MagickXGetAnnotateInfo GmMagickXGetAnnotateInfo #define MagickXGetImportInfo GmMagickXGetImportInfo #define MagickXGetMapInfo GmMagickXGetMapInfo #define MagickXGetPixelPacket GmMagickXGetPixelPacket #define MagickXGetResourceClass GmMagickXGetResourceClass #define MagickXGetResourceDatabase GmMagickXGetResourceDatabase #define MagickXGetResourceInfo GmMagickXGetResourceInfo #define MagickXGetResourceInstance GmMagickXGetResourceInstance #define MagickXGetScreenDensity GmMagickXGetScreenDensity #define MagickXGetWindowColor GmMagickXGetWindowColor #define MagickXGetWindowInfo GmMagickXGetWindowInfo #define MagickXHighlightEllipse GmMagickXHighlightEllipse #define MagickXHighlightLine GmMagickXHighlightLine #define MagickXHighlightRectangle GmMagickXHighlightRectangle #define MagickXImportImage GmMagickXImportImage #define MagickXInfoWidget GmMagickXInfoWidget #define MagickXInitializeWindows GmMagickXInitializeWindows #define MagickXListBrowserWidget GmMagickXListBrowserWidget #define MagickXMagickMonitor GmMagickXMagickMonitor #define MagickXMakeCursor GmMagickXMakeCursor #define MagickXMakeImage GmMagickXMakeImage #define MagickXMakeMagnifyImage GmMagickXMakeMagnifyImage #define MagickXMakeStandardColormap GmMagickXMakeStandardColormap #define MagickXMakeWindow GmMagickXMakeWindow #define MagickXMenuWidget GmMagickXMenuWidget #define MagickXMonitorWidget GmMagickXMonitorWidget #define MagickXNoticeWidget GmMagickXNoticeWidget #define MagickXPreferencesWidget GmMagickXPreferencesWidget #define MagickXQueryColorDatabase GmMagickXQueryColorDatabase #define MagickXQueryPosition GmMagickXQueryPosition #define MagickXRefreshWindow GmMagickXRefreshWindow #define MagickXRemoteCommand GmMagickXRemoteCommand #define MagickXRetainWindowColors GmMagickXRetainWindowColors #define MagickXSetCursorState GmMagickXSetCursorState #define MagickXSetWindows GmMagickXSetWindows #define MagickXSignalHandler GmMagickXSignalHandler #define MagickXTextViewWidget GmMagickXTextViewWidget #define MagickXTextViewWidgetNDL GmMagickXTextViewWidgetNDL #define MagickXUserPreferences GmMagickXUserPreferences #define MagickXWarning GmMagickXWarning #define MagickXWindowByID GmMagickXWindowByID #define MagickXWindowByName GmMagickXWindowByName #define MagickXWindowByProperty GmMagickXWindowByProperty #define MagnifyImage GmMagnifyImage #define MapBlob GmMapBlob #define MapImage GmMapImage #define MapImages GmMapImages #define MapModeToString GmMapModeToString #define MatteFloodfillImage GmMatteFloodfillImage #define MedianFilterImage GmMedianFilterImage #define MetricTypeToString GmMetricTypeToString #define MinifyImage GmMinifyImage #define ModifyCache GmModifyCache #define ModifyImage GmModifyImage #define Modulate GmModulate #define ModulateImage GmModulateImage #define MogrifyImage GmMogrifyImage #define MogrifyImageCommand GmMogrifyImageCommand #define MogrifyImages GmMogrifyImages #define MontageImageCommand GmMontageImageCommand #define MontageImages GmMontageImages #define MorphImages GmMorphImages #define MosaicImages GmMosaicImages #define MotionBlurImage GmMotionBlurImage #define MultilineCensus GmMultilineCensus #define NegateImage GmNegateImage #define NewImageList GmNewImageList #define NextImageProfile GmNextImageProfile #define NoiseTypeToString GmNoiseTypeToString #define NormalizeImage GmNormalizeImage #define OilPaintImage GmOilPaintImage #define OpaqueImage GmOpaqueImage #define OpenBlob GmOpenBlob #define OpenCacheView GmOpenCacheView #define OpenModule GmOpenModule #define OpenModules GmOpenModules #define OrderedDitherImage GmOrderedDitherImage #define OrientationTypeToString GmOrientationTypeToString #define PackbitsEncode2Image GmPackbitsEncode2Image #define PackbitsEncodeImage GmPackbitsEncodeImage #define PanicDestroyMagick GmPanicDestroyMagick #define PersistCache GmPersistCache #define PingBlob GmPingBlob #define PingImage GmPingImage #define PixelIterateDualModify GmPixelIterateDualModify #define PixelIterateDualNew GmPixelIterateDualNew #define PixelIterateDualRead GmPixelIterateDualRead #define PixelIterateMonoModify GmPixelIterateMonoModify #define PixelIterateMonoRead GmPixelIterateMonoRead #define PixelIterateMonoSet GmPixelIterateMonoSet #define PixelIterateTripleModify GmPixelIterateTripleModify #define PixelIterateTripleNew GmPixelIterateTripleNew #define PlasmaImage GmPlasmaImage #define PopImagePixels GmPopImagePixels #define PrependImageToList GmPrependImageToList #define ProfileImage GmProfileImage #define PurgeTemporaryFiles GmPurgeTemporaryFiles #define PurgeTemporaryFilesAsyncSafe GmPurgeTemporaryFilesAsyncSafe #define PushImagePixels GmPushImagePixels #define QuantizeImage GmQuantizeImage #define QuantizeImages GmQuantizeImages #define QuantumOperatorImage GmQuantumOperatorImage #define QuantumOperatorImageMultivalue GmQuantumOperatorImageMultivalue #define QuantumOperatorRegionImage GmQuantumOperatorRegionImage #define QuantumOperatorToString GmQuantumOperatorToString #define QuantumSampleTypeToString GmQuantumSampleTypeToString #define QuantumTypeToString GmQuantumTypeToString #define QueryColorDatabase GmQueryColorDatabase #define QueryColorname GmQueryColorname #define RGBTransformImage GmRGBTransformImage #define RaiseImage GmRaiseImage #define RandomChannelThresholdImage GmRandomChannelThresholdImage #define ReacquireMemory GmReacquireMemory #define ReadBlob GmReadBlob #define ReadBlobByte GmReadBlobByte #define ReadBlobLSBDouble GmReadBlobLSBDouble #define ReadBlobLSBDoubles GmReadBlobLSBDoubles #define ReadBlobLSBFloat GmReadBlobLSBFloat #define ReadBlobLSBFloats GmReadBlobLSBFloats #define ReadBlobLSBLong GmReadBlobLSBLong #define ReadBlobLSBLongs GmReadBlobLSBLongs #define ReadBlobLSBShort GmReadBlobLSBShort #define ReadBlobLSBShorts GmReadBlobLSBShorts #define ReadBlobLSBSignedLong GmReadBlobLSBSignedLong #define ReadBlobLSBSignedShort GmReadBlobLSBSignedShort #define ReadBlobMSBDouble GmReadBlobMSBDouble #define ReadBlobMSBDoubles GmReadBlobMSBDoubles #define ReadBlobMSBFloat GmReadBlobMSBFloat #define ReadBlobMSBFloats GmReadBlobMSBFloats #define ReadBlobMSBLong GmReadBlobMSBLong #define ReadBlobMSBLongs GmReadBlobMSBLongs #define ReadBlobMSBShort GmReadBlobMSBShort #define ReadBlobMSBShorts GmReadBlobMSBShorts #define ReadBlobMSBSignedLong GmReadBlobMSBSignedLong #define ReadBlobMSBSignedShort GmReadBlobMSBSignedShort #define ReadBlobString GmReadBlobString #define ReadBlobZC GmReadBlobZC #define ReadImage GmReadImage #define ReadInlineImage GmReadInlineImage #define ReallocateImageColormap GmReallocateImageColormap #define ReduceNoiseImage GmReduceNoiseImage #define ReferenceBlob GmReferenceBlob #define ReferenceCache GmReferenceCache #define ReferenceImage GmReferenceImage #define RegisterARTImage GmRegisterARTImage #define RegisterAVSImage GmRegisterAVSImage #define RegisterBMPImage GmRegisterBMPImage #define RegisterBRAILLEImage GmRegisterBRAILLEImage #define RegisterCALSImage GmRegisterCALSImage #define RegisterCAPTIONImage GmRegisterCAPTIONImage #define RegisterCINEONImage GmRegisterCINEONImage #define RegisterCMYKImage GmRegisterCMYKImage #define RegisterCUTImage GmRegisterCUTImage #define RegisterDCMImage GmRegisterDCMImage #define RegisterDCRAWImage GmRegisterDCRAWImage #define RegisterDIBImage GmRegisterDIBImage #define RegisterDPXImage GmRegisterDPXImage #define RegisterEPTImage GmRegisterEPTImage #define RegisterFAXImage GmRegisterFAXImage #define RegisterFITSImage GmRegisterFITSImage #define RegisterGIFImage GmRegisterGIFImage #define RegisterGRADIENTImage GmRegisterGRADIENTImage #define RegisterGRAYImage GmRegisterGRAYImage #define RegisterHISTOGRAMImage GmRegisterHISTOGRAMImage #define RegisterHRZImage GmRegisterHRZImage #define RegisterHTMLImage GmRegisterHTMLImage #define RegisterICONImage GmRegisterICONImage #define RegisterIDENTITYImage GmRegisterIDENTITYImage #define RegisterINFOImage GmRegisterINFOImage #define RegisterJNXImage GmRegisterJNXImage #define RegisterJP2Image GmRegisterJP2Image #define RegisterJPEGImage GmRegisterJPEGImage #define RegisterLABELImage GmRegisterLABELImage #define RegisterLOCALEImage GmRegisterLOCALEImage #define RegisterLOGOImage GmRegisterLOGOImage #define RegisterMACImage GmRegisterMACImage #define RegisterMAPImage GmRegisterMAPImage #define RegisterMATImage GmRegisterMATImage #define RegisterMATTEImage GmRegisterMATTEImage #define RegisterMETAImage GmRegisterMETAImage #define RegisterMIFFImage GmRegisterMIFFImage #define RegisterMONOImage GmRegisterMONOImage #define RegisterMPCImage GmRegisterMPCImage #define RegisterMPEGImage GmRegisterMPEGImage #define RegisterMPRImage GmRegisterMPRImage #define RegisterMSLImage GmRegisterMSLImage #define RegisterMTVImage GmRegisterMTVImage #define RegisterMVGImage GmRegisterMVGImage #define RegisterMagickInfo GmRegisterMagickInfo #define RegisterNULLImage GmRegisterNULLImage #define RegisterOTBImage GmRegisterOTBImage #define RegisterPALMImage GmRegisterPALMImage #define RegisterPCDImage GmRegisterPCDImage #define RegisterPCLImage GmRegisterPCLImage #define RegisterPCXImage GmRegisterPCXImage #define RegisterPDBImage GmRegisterPDBImage #define RegisterPDFImage GmRegisterPDFImage #define RegisterPICTImage GmRegisterPICTImage #define RegisterPIXImage GmRegisterPIXImage #define RegisterPLASMAImage GmRegisterPLASMAImage #define RegisterPNGImage GmRegisterPNGImage #define RegisterPNMImage GmRegisterPNMImage #define RegisterPREVIEWImage GmRegisterPREVIEWImage #define RegisterPS2Image GmRegisterPS2Image #define RegisterPS3Image GmRegisterPS3Image #define RegisterPSDImage GmRegisterPSDImage #define RegisterPSImage GmRegisterPSImage #define RegisterPWPImage GmRegisterPWPImage #define RegisterRGBImage GmRegisterRGBImage #define RegisterRLAImage GmRegisterRLAImage #define RegisterRLEImage GmRegisterRLEImage #define RegisterSCTImage GmRegisterSCTImage #define RegisterSFWImage GmRegisterSFWImage #define RegisterSGIImage GmRegisterSGIImage #define RegisterSTEGANOImage GmRegisterSTEGANOImage #define RegisterSUNImage GmRegisterSUNImage #define RegisterSVGImage GmRegisterSVGImage #define RegisterStaticModules GmRegisterStaticModules #define RegisterTGAImage GmRegisterTGAImage #define RegisterTIFFImage GmRegisterTIFFImage #define RegisterTILEImage GmRegisterTILEImage #define RegisterTIMImage GmRegisterTIMImage #define RegisterTOPOLImage GmRegisterTOPOLImage #define RegisterTTFImage GmRegisterTTFImage #define RegisterTXTImage GmRegisterTXTImage #define RegisterUILImage GmRegisterUILImage #define RegisterURLImage GmRegisterURLImage #define RegisterUYVYImage GmRegisterUYVYImage #define RegisterVICARImage GmRegisterVICARImage #define RegisterVIDImage GmRegisterVIDImage #define RegisterVIFFImage GmRegisterVIFFImage #define RegisterWBMPImage GmRegisterWBMPImage #define RegisterWEBPImage GmRegisterWEBPImage #define RegisterWMFImage GmRegisterWMFImage #define RegisterWPGImage GmRegisterWPGImage #define RegisterXBMImage GmRegisterXBMImage #define RegisterXCFImage GmRegisterXCFImage #define RegisterXCImage GmRegisterXCImage #define RegisterXImage GmRegisterXImage #define RegisterXPMImage GmRegisterXPMImage #define RegisterXWDImage GmRegisterXWDImage #define RegisterYUVImage GmRegisterYUVImage #define RemoveDefinitions GmRemoveDefinitions #define RemoveFirstImageFromList GmRemoveFirstImageFromList #define RemoveLastImageFromList GmRemoveLastImageFromList #define ReplaceImageColormap GmReplaceImageColormap #define ReplaceImageInList GmReplaceImageInList #define ResetImagePage GmResetImagePage #define ResetTimer GmResetTimer #define ResizeFilterToString GmResizeFilterToString #define ResizeImage GmResizeImage #define ResolutionTypeToString GmResolutionTypeToString #define ReverseImageList GmReverseImageList #define RollImage GmRollImage #define RotateImage GmRotateImage #define SampleImage GmSampleImage #define ScaleImage GmScaleImage #define SeekBlob GmSeekBlob #define SetBlobClosable GmSetBlobClosable #define SetBlobTemporary GmSetBlobTemporary #define SetCacheView GmSetCacheView #define SetCacheViewPixels GmSetCacheViewPixels #define SetClientFilename GmSetClientFilename #define SetClientName GmSetClientName #define SetClientPath GmSetClientPath #define SetDelegateInfo GmSetDelegateInfo #define SetErrorHandler GmSetErrorHandler #define SetExceptionInfo GmSetExceptionInfo #define SetFatalErrorHandler GmSetFatalErrorHandler #define SetGeometry GmSetGeometry #define SetImage GmSetImage #define SetImageAttribute GmSetImageAttribute #define SetImageChannelDepth GmSetImageChannelDepth #define SetImageClipMask GmSetImageClipMask #define SetImageColor GmSetImageColor #define SetImageColorRegion GmSetImageColorRegion #define SetImageCompositeMask GmSetImageCompositeMask #define SetImageDepth GmSetImageDepth #define SetImageEx GmSetImageEx #define SetImageInfo GmSetImageInfo #define SetImageOpacity GmSetImageOpacity #define SetImagePixels GmSetImagePixels #define SetImagePixelsEx GmSetImagePixelsEx #define SetImageProfile GmSetImageProfile #define SetImageType GmSetImageType #define SetImageVirtualPixelMethod GmSetImageVirtualPixelMethod #define SetLogEventMask GmSetLogEventMask #define SetLogFormat GmSetLogFormat #define SetMagickInfo GmSetMagickInfo #define SetMagickRegistry GmSetMagickRegistry #define SetMagickResourceLimit GmSetMagickResourceLimit #define SetMonitorHandler GmSetMonitorHandler #define SetWarningHandler GmSetWarningHandler #define ShadeImage GmShadeImage #define SharpenImage GmSharpenImage #define SharpenImageChannel GmSharpenImageChannel #define ShaveImage GmShaveImage #define ShearImage GmShearImage #define SignatureImage GmSignatureImage #define SolarizeImage GmSolarizeImage #define SortColormapByIntensity GmSortColormapByIntensity #define SpliceImageIntoList GmSpliceImageIntoList #define SplitImageList GmSplitImageList #define SpreadImage GmSpreadImage #define StartTimer GmStartTimer #define SteganoImage GmSteganoImage #define StereoImage GmStereoImage #define StopTimer GmStopTimer #define StorageTypeToString GmStorageTypeToString #define StretchTypeToString GmStretchTypeToString #define StringToArgv GmStringToArgv #define StringToChannelType GmStringToChannelType #define StringToColorspaceType GmStringToColorspaceType #define StringToCompositeOperator GmStringToCompositeOperator #define StringToCompressionType GmStringToCompressionType #define StringToDouble GmStringToDouble #define StringToEndianType GmStringToEndianType #define StringToFilterTypes GmStringToFilterTypes #define StringToGravityType GmStringToGravityType #define StringToHighlightStyle GmStringToHighlightStyle #define StringToImageType GmStringToImageType #define StringToInterlaceType GmStringToInterlaceType #define StringToList GmStringToList #define StringToMetricType GmStringToMetricType #define StringToNoiseType GmStringToNoiseType #define StringToOrientationType GmStringToOrientationType #define StringToPreviewType GmStringToPreviewType #define StringToQuantumOperator GmStringToQuantumOperator #define StringToResolutionType GmStringToResolutionType #define StringToResourceType GmStringToResourceType #define StringToVirtualPixelMethod GmStringToVirtualPixelMethod #define Strip GmStrip #define StripImage GmStripImage #define StyleTypeToString GmStyleTypeToString #define SubstituteString GmSubstituteString #define SwirlImage GmSwirlImage #define SyncCacheView GmSyncCacheView #define SyncCacheViewPixels GmSyncCacheViewPixels #define SyncImage GmSyncImage #define SyncImagePixels GmSyncImagePixels #define SyncImagePixelsEx GmSyncImagePixelsEx #define SyncNextImageInList GmSyncNextImageInList #define SystemCommand GmSystemCommand #define TellBlob GmTellBlob #define TextureImage GmTextureImage #define ThresholdImage GmThresholdImage #define ThrowLoggedException GmThrowLoggedException #define ThumbnailImage GmThumbnailImage #define TimeImageCommand GmTimeImageCommand #define Tokenizer GmTokenizer #define TransformColorspace GmTransformColorspace #define TransformHSL GmTransformHSL #define TransformHWB GmTransformHWB #define TransformImage GmTransformImage #define TransformRGBImage GmTransformRGBImage #define TransformSignature GmTransformSignature #define TranslateText GmTranslateText #define TranslateTextEx GmTranslateTextEx #define TransparentImage GmTransparentImage #define UnlockSemaphoreInfo GmUnlockSemaphoreInfo #define UnmapBlob GmUnmapBlob #define UnregisterARTImage GmUnregisterARTImage #define UnregisterAVSImage GmUnregisterAVSImage #define UnregisterBMPImage GmUnregisterBMPImage #define UnregisterBRAILLEImage GmUnregisterBRAILLEImage #define UnregisterCALSImage GmUnregisterCALSImage #define UnregisterCAPTIONImage GmUnregisterCAPTIONImage #define UnregisterCINEONImage GmUnregisterCINEONImage #define UnregisterCMYKImage GmUnregisterCMYKImage #define UnregisterCUTImage GmUnregisterCUTImage #define UnregisterDCMImage GmUnregisterDCMImage #define UnregisterDCRAWImage GmUnregisterDCRAWImage #define UnregisterDIBImage GmUnregisterDIBImage #define UnregisterDPXImage GmUnregisterDPXImage #define UnregisterEPTImage GmUnregisterEPTImage #define UnregisterFAXImage GmUnregisterFAXImage #define UnregisterFITSImage GmUnregisterFITSImage #define UnregisterGIFImage GmUnregisterGIFImage #define UnregisterGRADIENTImage GmUnregisterGRADIENTImage #define UnregisterGRAYImage GmUnregisterGRAYImage #define UnregisterHISTOGRAMImage GmUnregisterHISTOGRAMImage #define UnregisterHRZImage GmUnregisterHRZImage #define UnregisterHTMLImage GmUnregisterHTMLImage #define UnregisterICONImage GmUnregisterICONImage #define UnregisterIDENTITYImage GmUnregisterIDENTITYImage #define UnregisterINFOImage GmUnregisterINFOImage #define UnregisterJNXImage GmUnregisterJNXImage #define UnregisterJP2Image GmUnregisterJP2Image #define UnregisterJPEGImage GmUnregisterJPEGImage #define UnregisterLABELImage GmUnregisterLABELImage #define UnregisterLOCALEImage GmUnregisterLOCALEImage #define UnregisterLOGOImage GmUnregisterLOGOImage #define UnregisterMACImage GmUnregisterMACImage #define UnregisterMAPImage GmUnregisterMAPImage #define UnregisterMATImage GmUnregisterMATImage #define UnregisterMATTEImage GmUnregisterMATTEImage #define UnregisterMETAImage GmUnregisterMETAImage #define UnregisterMIFFImage GmUnregisterMIFFImage #define UnregisterMONOImage GmUnregisterMONOImage #define UnregisterMPCImage GmUnregisterMPCImage #define UnregisterMPEGImage GmUnregisterMPEGImage #define UnregisterMPRImage GmUnregisterMPRImage #define UnregisterMSLImage GmUnregisterMSLImage #define UnregisterMTVImage GmUnregisterMTVImage #define UnregisterMVGImage GmUnregisterMVGImage #define UnregisterMagickInfo GmUnregisterMagickInfo #define UnregisterNULLImage GmUnregisterNULLImage #define UnregisterOTBImage GmUnregisterOTBImage #define UnregisterPALMImage GmUnregisterPALMImage #define UnregisterPCDImage GmUnregisterPCDImage #define UnregisterPCLImage GmUnregisterPCLImage #define UnregisterPCXImage GmUnregisterPCXImage #define UnregisterPDBImage GmUnregisterPDBImage #define UnregisterPDFImage GmUnregisterPDFImage #define UnregisterPICTImage GmUnregisterPICTImage #define UnregisterPIXImage GmUnregisterPIXImage #define UnregisterPLASMAImage GmUnregisterPLASMAImage #define UnregisterPNGImage GmUnregisterPNGImage #define UnregisterPNMImage GmUnregisterPNMImage #define UnregisterPREVIEWImage GmUnregisterPREVIEWImage #define UnregisterPS2Image GmUnregisterPS2Image #define UnregisterPS3Image GmUnregisterPS3Image #define UnregisterPSDImage GmUnregisterPSDImage #define UnregisterPSImage GmUnregisterPSImage #define UnregisterPWPImage GmUnregisterPWPImage #define UnregisterRGBImage GmUnregisterRGBImage #define UnregisterRLAImage GmUnregisterRLAImage #define UnregisterRLEImage GmUnregisterRLEImage #define UnregisterSCTImage GmUnregisterSCTImage #define UnregisterSFWImage GmUnregisterSFWImage #define UnregisterSGIImage GmUnregisterSGIImage #define UnregisterSTEGANOImage GmUnregisterSTEGANOImage #define UnregisterSUNImage GmUnregisterSUNImage #define UnregisterSVGImage GmUnregisterSVGImage #define UnregisterStaticModules GmUnregisterStaticModules #define UnregisterTGAImage GmUnregisterTGAImage #define UnregisterTIFFImage GmUnregisterTIFFImage #define UnregisterTILEImage GmUnregisterTILEImage #define UnregisterTIMImage GmUnregisterTIMImage #define UnregisterTOPOLImage GmUnregisterTOPOLImage #define UnregisterTTFImage GmUnregisterTTFImage #define UnregisterTXTImage GmUnregisterTXTImage #define UnregisterUILImage GmUnregisterUILImage #define UnregisterURLImage GmUnregisterURLImage #define UnregisterUYVYImage GmUnregisterUYVYImage #define UnregisterVICARImage GmUnregisterVICARImage #define UnregisterVIDImage GmUnregisterVIDImage #define UnregisterVIFFImage GmUnregisterVIFFImage #define UnregisterWBMPImage GmUnregisterWBMPImage #define UnregisterWEBPImage GmUnregisterWEBPImage #define UnregisterWMFImage GmUnregisterWMFImage #define UnregisterWPGImage GmUnregisterWPGImage #define UnregisterXBMImage GmUnregisterXBMImage #define UnregisterXCFImage GmUnregisterXCFImage #define UnregisterXCImage GmUnregisterXCImage #define UnregisterXImage GmUnregisterXImage #define UnregisterXPMImage GmUnregisterXPMImage #define UnregisterXWDImage GmUnregisterXWDImage #define UnregisterYUVImage GmUnregisterYUVImage #define UnsharpMaskImage GmUnsharpMaskImage #define UnsharpMaskImageChannel GmUnsharpMaskImageChannel #define UpdateSignature GmUpdateSignature #define WaveImage GmWaveImage #define WhiteThresholdImage GmWhiteThresholdImage #define WriteBlob GmWriteBlob #define WriteBlobByte GmWriteBlobByte #define WriteBlobFile GmWriteBlobFile #define WriteBlobLSBLong GmWriteBlobLSBLong #define WriteBlobLSBShort GmWriteBlobLSBShort #define WriteBlobLSBSignedLong GmWriteBlobLSBSignedLong #define WriteBlobLSBSignedShort GmWriteBlobLSBSignedShort #define WriteBlobMSBLong GmWriteBlobMSBLong #define WriteBlobMSBShort GmWriteBlobMSBShort #define WriteBlobMSBSignedLong GmWriteBlobMSBSignedLong #define WriteBlobMSBSignedShort GmWriteBlobMSBSignedShort #define WriteBlobString GmWriteBlobString #define WriteBlobStringEOL GmWriteBlobStringEOL #define WriteBlobStringWithEOL GmWriteBlobStringWithEOL #define WriteImage GmWriteImage #define WriteImages GmWriteImages #define WriteImagesFile GmWriteImagesFile #define ZoomImage GmZoomImage #endif /* defined(PREFIX_MAGICK_SYMBOLS) */ #endif /* defined(_MAGICK_SYMBOLS_H) */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/texture.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Texture Methods. */ #ifndef _MAGICK_TEXTURE_H #define _MAGICK_TEXTURE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" extern MagickExport Image *ConstituteTextureImage(const unsigned long columns,const unsigned long rows, const Image *texture,ExceptionInfo *exception); extern MagickExport MagickPassFail TextureImage(Image *,const Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_TEXTURE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/timer.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Timer Methods. */ #ifndef _MAGICK_TIMER_H #define _MAGICK_TIMER_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { UndefinedTimerState, StoppedTimerState, RunningTimerState } TimerState; /* Typedef declarations. */ typedef struct _Timer { double start, stop, total; } Timer; typedef struct _TimerInfo { Timer user, elapsed; TimerState state; unsigned long signature; } TimerInfo; /* Timer methods. */ extern MagickExport double GetElapsedTime(TimerInfo *), GetUserTime(TimerInfo *), GetTimerResolution(void); extern MagickExport unsigned int ContinueTimer(TimerInfo *); extern MagickExport void GetTimerInfo(TimerInfo *), ResetTimer(TimerInfo *), StartTimer(TimerInfo *time_info,const unsigned int reset), StopTimer(TimerInfo *time_info); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/transform.h ================================================ /* Copyright (C) 2003 - 2010 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Transform Methods. */ #ifndef _MAGICK_TRANSFORM_H #define _MAGICK_TRANSFORM_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info,ExceptionInfo *exception), *CoalesceImages(const Image *image,ExceptionInfo *exception), *CropImage(const Image *image,const RectangleInfo *geometry,ExceptionInfo *exception), *DeconstructImages(const Image *image,ExceptionInfo *exception), *ExtentImage(const Image *image,const RectangleInfo *geometry,ExceptionInfo *exception), *FlattenImages(const Image *image,ExceptionInfo *exception), *FlipImage(const Image *image,ExceptionInfo *exception), *FlopImage(const Image *image,ExceptionInfo *exception), *MosaicImages(const Image *image,ExceptionInfo *exception), *RollImage(const Image *image,const long x_offset,const long y_offset,ExceptionInfo *exception), *ShaveImage(const Image *image,const RectangleInfo *shave_info,ExceptionInfo *exception); extern MagickExport MagickPassFail TransformImage(Image **,const char *,const char *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_TRANSFORM_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/type.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Drawing methods. */ #ifndef _MAGICK_TYPE_H #define _MAGICK_TYPE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { NormalStretch, UltraCondensedStretch, ExtraCondensedStretch, CondensedStretch, SemiCondensedStretch, SemiExpandedStretch, ExpandedStretch, ExtraExpandedStretch, UltraExpandedStretch, AnyStretch } StretchType; typedef enum { NormalStyle, ItalicStyle, ObliqueStyle, AnyStyle } StyleType; /* Typedef declarations. */ typedef struct _TypeInfo { char *path, *name, *description, *family; StyleType style; StretchType stretch; unsigned long weight; char *encoding, *foundry, *format, *metrics, *glyphs; unsigned int stealth; unsigned long signature; struct _TypeInfo *previous, *next; } TypeInfo; /* Method declarations. */ extern MagickExport char **GetTypeList(const char *,unsigned long *); extern MagickExport MagickPassFail ListTypeInfo(FILE *,ExceptionInfo *); extern MagickExport const TypeInfo *GetTypeInfo(const char *,ExceptionInfo *), *GetTypeInfoByFamily(const char *,const StyleType,const StretchType, const unsigned long,ExceptionInfo *); #if defined(MAGICK_IMPLEMENTATION) # include "magick/type-private.h" #endif /* MAGICK_IMPLEMENTATION */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_TYPE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/utility.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Utility Methods. */ #ifndef _MAGICK_UTILITY_H #define _MAGICK_UTILITY_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { RootPath, HeadPath, TailPath, BasePath, ExtensionPath, MagickPath, SubImagePath, FullPath } PathType; /* Typedef declarations. */ typedef struct _TokenInfo { int state; unsigned int flag; long offset; char quote; } TokenInfo; /* Utilities methods. */ #undef ARG_NOT_USED #define ARG_NOT_USED(arg) (void) arg /* A callback function which behaves similar to strlcpy() except which optionally translates text while it is copied and always returns the number of characters which were actually copied rather than the number of characters which were available to copy. */ typedef size_t (*MagickTextTranslate)(char *dst, const char *src, const size_t size); extern MagickExport char *AcquireString(const char *), *AllocateString(const char *), *Base64Encode(const unsigned char *,const size_t,size_t *), *EscapeString(const char *,const char), *GetPageGeometry(const char *), **ListFiles(const char *,const char *,long *), **StringToArgv(const char *,int *), **StringToList(const char *), *TranslateText(const ImageInfo *,Image *,const char *), *TranslateTextEx(const ImageInfo *,Image *,const char *,MagickTextTranslate); extern MagickExport const char *GetClientFilename(void) MAGICK_FUNC_CONST, *GetClientName(void) MAGICK_FUNC_CONST, *GetClientPath(void) MAGICK_FUNC_CONST, *SetClientFilename(const char *), *SetClientName(const char *), *SetClientPath(const char *); extern MagickExport double StringToDouble(const char *,const double); extern MagickExport int GetGeometry(const char *,long *,long *,unsigned long *,unsigned long *), GlobExpression(const char *,const char *) MAGICK_FUNC_PURE, LocaleNCompare(const char *,const char *,const size_t) MAGICK_FUNC_PURE, LocaleCompare(const char *,const char *) MAGICK_FUNC_PURE, GetMagickDimension(const char *str,double *width,double *height,double *xoff,double *yoff), GetMagickGeometry(const char *geometry,long *x,long *y,unsigned long *width, unsigned long *height), MagickRandReentrant(unsigned int *seed) MAGICK_FUNC_DEPRECATED, MagickSpawnVP(const unsigned int verbose, const char *file, char *const argv[]), SystemCommand(const unsigned int,const char *), Tokenizer(TokenInfo *,unsigned,char *,size_t,char *,char *,char *,char *, char,char *,int *,char *); extern MagickExport unsigned int MagickRandNewSeed(void) MAGICK_FUNC_DEPRECATED; extern MagickExport unsigned char *Base64Decode(const char *, size_t *); extern MagickExport MagickPassFail CloneString(char **,const char *), ConcatenateString(char **,const char *), ExpandFilenames(int *,char ***), GetExecutionPath(char *), GetExecutionPathUsingName(char *), MagickCreateDirectoryPath(const char *dir,ExceptionInfo *exception); extern MagickExport MagickBool IsAccessible(const char *), IsAccessibleNoLogging(const char *), IsAccessibleAndNotEmpty(const char *), IsGeometry(const char *), IsGlob(const char *) MAGICK_FUNC_PURE, IsWriteable(const char *), MagickSceneFileName(char *filename,const char* filename_template, const char* scene_template,const MagickBool force,unsigned long scene), SubstituteString(char **buffer,const char *search,const char *replace); extern MagickExport unsigned long MultilineCensus(const char *) MAGICK_FUNC_PURE; extern MagickExport void AppendImageFormat(const char *,char *), DefineClientName(const char *), DefineClientPathAndName(const char *), ExpandFilename(char *), FormatSize(const magick_int64_t size,char *format), GetPathComponent(const char *,PathType,char *), GetToken(const char *,char **,char *) MAGICK_FUNC_DEPRECATED, LocaleLower(char *), LocaleUpper(char *), Strip(char *), SetGeometry(const Image *,RectangleInfo *); extern MagickExport void FormatString(char *string,const char *format,...) MAGICK_ATTRIBUTE((__format__ (__printf__,2,3))), FormatStringList(char *string,const char *format,va_list operands) MAGICK_ATTRIBUTE((__format__ (__printf__,2,0))), MagickFormatString(char *string,const size_t length,const char *format,...) MAGICK_ATTRIBUTE((__format__ (__printf__,3,4))), MagickFormatStringList(char *string,const size_t length,const char *format,va_list operands) MAGICK_ATTRIBUTE((__format__ (__printf__,3,0))); extern MagickExport magick_int64_t MagickSizeStrToInt64(const char *str,const unsigned int kilo); extern MagickExport size_t MagickGetToken(const char *start,char **end,char *token, const size_t buffer_length), MagickStripSpacesFromString(char *string), MagickStrlCat(char *dst, const char *src, const size_t size) MAGICK_FUNC_NONNULL, MagickStrlCpy(char *dst, const char *src, const size_t size) MAGICK_FUNC_NONNULL, MagickStrlCpyTrunc(char *dst, const char *src, const size_t size) MAGICK_FUNC_NONNULL; #if defined(MAGICK_IMPLEMENTATION) # include "magick/utility-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/magick/version.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick version and copyright. */ #ifndef _MAGICK_VERSION_H #define _MAGICK_VERSION_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Define declarations. MagickLibVersion and MagickLibVersionNumber are defined differently than they are in ImageMagick. The three fields are based on library interface versioning. Each field in MagickLibVersion is one byte. The most significant field (third byte from the right) defines the library major interface, which is incremented whenever the library ABI changes incompatibly with preceding versions. The second field identifies an interface (a span) in a series of upward-compatible interfaces with the same major interface (such as when only new functions have) been added. The least significant field specifies the revision across 100% compatible interfaces. MagickLibVersionText provides a simple human-readable string for identifying the release. */ #define MagickPackageName "GraphicsMagick" #define MagickCopyright "Copyright (C) 2002-2020 GraphicsMagick Group.\nAdditional copyrights and licenses apply to this software.\nSee http://www.GraphicsMagick.org/www/Copyright.html for details." #define MagickLibVersion 0x242100 #define MagickLibVersionText "1.3.35" #define MagickLibVersionNumber 24,21,0 #define MagickChangeDate "20200223" #define MagickReleaseDate "2020-02-23" /* The MagickLibInterfaceNewest and MagickLibInterfaceOldest defines provide both the newest and oldest interfaces supported by the library. The 'newest' interface is incremented if new interfaces are added to the library. The 'oldest' interface is reset to the value of 'newest' if an existing interface is changed incompatibly, or an interface is removed. This scheme is similar to that used by ELF libraries. Note that the values used are related to those in MagickLibVersionNumber, but these are broken out and simplified so that they can be easily used in C pre-processor logic. */ #define MagickLibInterfaceNewest 24 #define MagickLibInterfaceOldest 3 #if (QuantumDepth == 8) #define MagickQuantumDepth "Q8" #elif (QuantumDepth == 16) #define MagickQuantumDepth "Q16" #elif (QuantumDepth == 32) #define MagickQuantumDepth "Q32" #else # error Unsupported quantum depth. #endif #define MagickVersion MagickPackageName " " MagickLibVersionText " " \ MagickReleaseDate " " MagickQuantumDepth " " MagickWebSite #define MagickWebSite "http://www." MagickPackageName ".org/" /* Method declarations. */ extern MagickExport const char *GetMagickCopyright(void) MAGICK_FUNC_CONST, *GetMagickVersion(unsigned long *) MAGICK_FUNC_CONST, *GetMagickWebSite(void) MAGICK_FUNC_CONST; #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/wand/drawing_wand.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group */ /* ImageMagick Drawing Wand API. */ #ifndef _MAGICK_DRAWING_WAND_H #define _MAGICK_DRAWING_WAND_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "wand/wand_symbols.h" #include "wand/pixel_wand.h" #undef CloneDrawingWand #define CloneDrawingWand MagickCloneDrawingWand #undef DestroyDrawingWand #define DestroyDrawingWand MagickDestroyDrawingWand #undef DrawAffine #define DrawAffine MagickDrawAffine #undef DrawAllocateWand #define DrawAllocateWand MagickDrawAllocateWand #undef DrawAnnotation #define DrawAnnotation MagickDrawAnnotation #undef DrawArc #define DrawArc MagickDrawArc #undef DrawBezier #define DrawBezier MagickDrawBezier #undef DrawClearException #define DrawClearException MagickDrawClearException #undef DrawCircle #define DrawCircle MagickDrawCircle #undef DrawColor #define DrawColor MagickDrawColor #undef DrawComment #define DrawComment MagickDrawComment #undef DrawComposite #define DrawComposite MagickDrawComposite #undef DrawEllipse #define DrawEllipse MagickDrawEllipse #undef DrawGetClipPath #define DrawGetClipPath MagickDrawGetClipPath #undef DrawGetClipRule #define DrawGetClipRule MagickDrawGetClipRule #undef DrawGetClipUnits #define DrawGetClipUnits MagickDrawGetClipUnits #undef DrawGetException #define DrawGetException MagickDrawGetException #undef DrawGetFillColor #define DrawGetFillColor MagickDrawGetFillColor #undef DrawGetFillOpacity #define DrawGetFillOpacity MagickDrawGetFillOpacity #undef DrawGetFillRule #define DrawGetFillRule MagickDrawGetFillRule #undef DrawGetFont #define DrawGetFont MagickDrawGetFont #undef DrawGetFontFamily #define DrawGetFontFamily MagickDrawGetFontFamily #undef DrawGetFontSize #define DrawGetFontSize MagickDrawGetFontSize #undef DrawGetFontStretch #define DrawGetFontStretch MagickDrawGetFontStretch #undef DrawGetFontStyle #define DrawGetFontStyle MagickDrawGetFontStyle #undef DrawGetFontWeight #define DrawGetFontWeight MagickDrawGetFontWeight #undef DrawGetGravity #define DrawGetGravity MagickDrawGetGravity #undef DrawGetStrokeAntialias #define DrawGetStrokeAntialias MagickDrawGetStrokeAntialias #undef DrawGetStrokeColor #define DrawGetStrokeColor MagickDrawGetStrokeColor #undef DrawGetStrokeDashArray #define DrawGetStrokeDashArray MagickDrawGetStrokeDashArray #undef DrawGetStrokeDashOffset #define DrawGetStrokeDashOffset MagickDrawGetStrokeDashOffset #undef DrawGetStrokeLineCap #define DrawGetStrokeLineCap MagickDrawGetStrokeLineCap #undef DrawGetStrokeLineJoin #define DrawGetStrokeLineJoin MagickDrawGetStrokeLineJoin #undef DrawGetStrokeMiterLimit #define DrawGetStrokeMiterLimit MagickDrawGetStrokeMiterLimit #undef DrawGetStrokeOpacity #define DrawGetStrokeOpacity MagickDrawGetStrokeOpacity #undef DrawGetStrokeWidth #define DrawGetStrokeWidth MagickDrawGetStrokeWidth #undef DrawGetTextAntialias #define DrawGetTextAntialias MagickDrawGetTextAntialias #undef DrawGetTextDecoration #define DrawGetTextDecoration MagickDrawGetTextDecoration #undef DrawGetTextEncoding #define DrawGetTextEncoding MagickDrawGetTextEncoding #undef DrawGetTextUnderColor #define DrawGetTextUnderColor MagickDrawGetTextUnderColor #undef DrawLine #define DrawLine MagickDrawLine #undef DrawMatte #define DrawMatte MagickDrawMatte #undef DrawPathClose #define DrawPathClose MagickDrawPathClose #undef DrawPathCurveToAbsolute #define DrawPathCurveToAbsolute MagickDrawPathCurveToAbsolute #undef DrawPathCurveToQuadraticBezierAbsolute #define DrawPathCurveToQuadraticBezierAbsolute MagickDrawPathCurveToQuadraticBezierAbsolute #undef DrawPathCurveToQuadraticBezierRelative #define DrawPathCurveToQuadraticBezierRelative MagickDrawPathCurveToQuadraticBezierRelative #undef DrawPathCurveToQuadraticBezierSmoothAbsolute #define DrawPathCurveToQuadraticBezierSmoothAbsolute MagickDrawPathCurveToQuadraticBezierSmoothAbsolute #undef DrawPathCurveToQuadraticBezierSmoothRelative #define DrawPathCurveToQuadraticBezierSmoothRelative MagickDrawPathCurveToQuadraticBezierSmoothRelative #undef DrawPathCurveToRelative #define DrawPathCurveToRelative MagickDrawPathCurveToRelative #undef DrawPathCurveToSmoothAbsolute #define DrawPathCurveToSmoothAbsolute MagickDrawPathCurveToSmoothAbsolute #undef DrawPathCurveToSmoothRelative #define DrawPathCurveToSmoothRelative MagickDrawPathCurveToSmoothRelative #undef DrawPathEllipticArcAbsolute #define DrawPathEllipticArcAbsolute MagickDrawPathEllipticArcAbsolute #undef DrawPathEllipticArcRelative #define DrawPathEllipticArcRelative MagickDrawPathEllipticArcRelative #undef DrawPathFinish #define DrawPathFinish MagickDrawPathFinish #undef DrawPathLineToAbsolute #define DrawPathLineToAbsolute MagickDrawPathLineToAbsolute #undef DrawPathLineToHorizontalAbsolute #define DrawPathLineToHorizontalAbsolute MagickDrawPathLineToHorizontalAbsolute #undef DrawPathLineToHorizontalRelative #define DrawPathLineToHorizontalRelative MagickDrawPathLineToHorizontalRelative #undef DrawPathLineToRelative #define DrawPathLineToRelative MagickDrawPathLineToRelative #undef DrawPathLineToVerticalAbsolute #define DrawPathLineToVerticalAbsolute MagickDrawPathLineToVerticalAbsolute #undef DrawPathLineToVerticalRelative #define DrawPathLineToVerticalRelative MagickDrawPathLineToVerticalRelative #undef DrawPathMoveToAbsolute #define DrawPathMoveToAbsolute MagickDrawPathMoveToAbsolute #undef DrawPathMoveToRelative #define DrawPathMoveToRelative MagickDrawPathMoveToRelative #undef DrawPathStart #define DrawPathStart MagickDrawPathStart #undef DrawPeekGraphicContext #define DrawPeekGraphicContext MagickDrawPeekGraphicContext #undef DrawPoint #define DrawPoint MagickDrawPoint #undef DrawPolygon #define DrawPolygon MagickDrawPolygon #undef DrawPolyline #define DrawPolyline MagickDrawPolyline #undef DrawPopClipPath #define DrawPopClipPath MagickDrawPopClipPath #undef DrawPopDefs #define DrawPopDefs MagickDrawPopDefs #undef DrawPopGraphicContext #define DrawPopGraphicContext MagickDrawPopGraphicContext #undef DrawPopPattern #define DrawPopPattern MagickDrawPopPattern #undef DrawPushClipPath #define DrawPushClipPath MagickDrawPushClipPath #undef DrawPushDefs #define DrawPushDefs MagickDrawPushDefs #undef DrawPushGraphicContext #define DrawPushGraphicContext MagickDrawPushGraphicContext #undef DrawPushPattern #define DrawPushPattern MagickDrawPushPattern #undef DrawRectangle #define DrawRectangle MagickDrawRectangle #undef DrawRender #define DrawRender MagickDrawRender #undef DrawRotate #define DrawRotate MagickDrawRotate #undef DrawRoundRectangle #define DrawRoundRectangle MagickDrawRoundRectangle #undef DrawScale #define DrawScale MagickDrawScale #undef DrawSetClipPath #define DrawSetClipPath MagickDrawSetClipPath #undef DrawSetClipRule #define DrawSetClipRule MagickDrawSetClipRule #undef DrawSetClipUnits #define DrawSetClipUnits MagickDrawSetClipUnits #undef DrawSetFillColor #define DrawSetFillColor MagickDrawSetFillColor #undef DrawSetFillOpacity #define DrawSetFillOpacity MagickDrawSetFillOpacity #undef DrawSetFillPatternURL #define DrawSetFillPatternURL MagickDrawSetFillPatternURL #undef DrawSetFillRule #define DrawSetFillRule MagickDrawSetFillRule #undef DrawSetFont #define DrawSetFont MagickDrawSetFont #undef DrawSetFontFamily #define DrawSetFontFamily MagickDrawSetFontFamily #undef DrawSetFontSize #define DrawSetFontSize MagickDrawSetFontSize #undef DrawSetFontStretch #define DrawSetFontStretch MagickDrawSetFontStretch #undef DrawSetFontStyle #define DrawSetFontStyle MagickDrawSetFontStyle #undef DrawSetFontWeight #define DrawSetFontWeight MagickDrawSetFontWeight #undef DrawSetGravity #define DrawSetGravity MagickDrawSetGravity #undef DrawSetStrokeAntialias #define DrawSetStrokeAntialias MagickDrawSetStrokeAntialias #undef DrawSetStrokeColor #define DrawSetStrokeColor MagickDrawSetStrokeColor #undef DrawSetStrokeDashArray #define DrawSetStrokeDashArray MagickDrawSetStrokeDashArray #undef DrawSetStrokeDashOffset #define DrawSetStrokeDashOffset MagickDrawSetStrokeDashOffset #undef DrawSetStrokeLineCap #define DrawSetStrokeLineCap MagickDrawSetStrokeLineCap #undef DrawSetStrokeLineJoin #define DrawSetStrokeLineJoin MagickDrawSetStrokeLineJoin #undef DrawSetStrokeMiterLimit #define DrawSetStrokeMiterLimit MagickDrawSetStrokeMiterLimit #undef DrawSetStrokeOpacity #define DrawSetStrokeOpacity MagickDrawSetStrokeOpacity #undef DrawSetStrokePatternURL #define DrawSetStrokePatternURL MagickDrawSetStrokePatternURL #undef DrawSetStrokeWidth #define DrawSetStrokeWidth MagickDrawSetStrokeWidth #undef DrawSetTextAntialias #define DrawSetTextAntialias MagickDrawSetTextAntialias #undef DrawSetTextDecoration #define DrawSetTextDecoration MagickDrawSetTextDecoration #undef DrawSetTextEncoding #define DrawSetTextEncoding MagickDrawSetTextEncoding #undef DrawSetTextUnderColor #define DrawSetTextUnderColor MagickDrawSetTextUnderColor #undef DrawSetViewbox #define DrawSetViewbox MagickDrawSetViewbox #undef DrawSkewX #define DrawSkewX MagickDrawSkewX #undef DrawSkewY #define DrawSkewY MagickDrawSkewY #undef DrawTranslate #define DrawTranslate MagickDrawTranslate #undef NewDrawingWand #define NewDrawingWand MagickNewDrawingWand typedef struct _DrawingWand DrawingWand; extern WandExport char *DrawGetClipPath(const DrawingWand *), *DrawGetException(const DrawingWand *,ExceptionType *), *DrawGetFont(const DrawingWand *), *DrawGetFontFamily(const DrawingWand *), *DrawGetTextEncoding(const DrawingWand *); extern WandExport ClipPathUnits DrawGetClipUnits(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport DecorationType DrawGetTextDecoration(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport double DrawGetFillOpacity(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetFontSize(const DrawingWand *) MAGICK_FUNC_PURE, *DrawGetStrokeDashArray(const DrawingWand *,unsigned long *), DrawGetStrokeDashOffset(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetStrokeOpacity(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetStrokeWidth(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport DrawInfo *DrawPeekGraphicContext(const DrawingWand *); extern WandExport DrawingWand *CloneDrawingWand(const DrawingWand *drawing_wand), *DrawAllocateWand(const DrawInfo *,Image *) MAGICK_ATTRIBUTE ((deprecated)), *NewDrawingWand(void); extern WandExport FillRule DrawGetClipRule(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetFillRule(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport GravityType DrawGetGravity(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport LineCap DrawGetStrokeLineCap(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport LineJoin DrawGetStrokeLineJoin(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport StretchType DrawGetFontStretch(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport StyleType DrawGetFontStyle(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport unsigned int DrawClearException(DrawingWand *), DrawGetStrokeAntialias(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetTextAntialias(const DrawingWand *) MAGICK_FUNC_PURE, DrawRender(const DrawingWand *) MAGICK_ATTRIBUTE ((deprecated)); /* Use MagickDrawImage() instead */ extern WandExport unsigned long DrawGetFontWeight(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetStrokeMiterLimit(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport void DrawAffine(DrawingWand *,const AffineMatrix *), DrawAnnotation(DrawingWand *,const double,const double,const unsigned char *), DrawArc(DrawingWand *,const double,const double,const double,const double, const double,const double), DrawBezier(DrawingWand *,const unsigned long,const PointInfo *), DrawCircle(DrawingWand *,const double,const double,const double,const double), DrawColor(DrawingWand *,const double,const double,const PaintMethod), DrawComment(DrawingWand *,const char *), DestroyDrawingWand(DrawingWand *), DrawEllipse(DrawingWand *,const double,const double,const double,const double, const double,const double), DrawComposite(DrawingWand *,const CompositeOperator,const double,const double, const double,const double,const Image *), DrawGetFillColor(const DrawingWand *,PixelWand *), DrawGetStrokeColor(const DrawingWand *,PixelWand *), DrawGetTextUnderColor(const DrawingWand *,PixelWand *), DrawLine(DrawingWand *,const double, const double,const double,const double), DrawMatte(DrawingWand *,const double,const double,const PaintMethod), DrawPathClose(DrawingWand *), DrawPathCurveToAbsolute(DrawingWand *,const double,const double,const double, const double,const double,const double), DrawPathCurveToRelative(DrawingWand *,const double,const double,const double, const double,const double, const double), DrawPathCurveToQuadraticBezierAbsolute(DrawingWand *,const double, const double,const double,const double), DrawPathCurveToQuadraticBezierRelative(DrawingWand *,const double, const double,const double,const double), DrawPathCurveToQuadraticBezierSmoothAbsolute(DrawingWand *,const double, const double), DrawPathCurveToQuadraticBezierSmoothRelative(DrawingWand *,const double, const double), DrawPathCurveToSmoothAbsolute(DrawingWand *,const double,const double, const double,const double), DrawPathCurveToSmoothRelative(DrawingWand *,const double,const double, const double,const double), DrawPathEllipticArcAbsolute(DrawingWand *,const double,const double, const double,unsigned int,unsigned int,const double,const double), DrawPathEllipticArcRelative(DrawingWand *,const double,const double, const double,unsigned int,unsigned int,const double,const double), DrawPathFinish(DrawingWand *), DrawPathLineToAbsolute(DrawingWand *,const double,const double), DrawPathLineToRelative(DrawingWand *,const double,const double), DrawPathLineToHorizontalAbsolute(DrawingWand *,const double), DrawPathLineToHorizontalRelative(DrawingWand *,const double), DrawPathLineToVerticalAbsolute(DrawingWand *,const double), DrawPathLineToVerticalRelative(DrawingWand *,const double), DrawPathMoveToAbsolute(DrawingWand *,const double,const double), DrawPathMoveToRelative(DrawingWand *,const double,const double), DrawPathStart(DrawingWand *), DrawPoint(DrawingWand *,const double,const double), DrawPolygon(DrawingWand *,const unsigned long,const PointInfo *), DrawPolyline(DrawingWand *,const unsigned long,const PointInfo *), DrawPopClipPath(DrawingWand *), DrawPopDefs(DrawingWand *), DrawPopGraphicContext(DrawingWand *), DrawPopPattern(DrawingWand *), DrawPushClipPath(DrawingWand *,const char *), DrawPushDefs(DrawingWand *), DrawPushGraphicContext(DrawingWand *), DrawPushPattern(DrawingWand *,const char *,const double,const double, const double,const double), DrawRectangle(DrawingWand *,const double,const double,const double, const double), DrawRotate(DrawingWand *,const double), DrawRoundRectangle(DrawingWand *,double,double,double,double,double,double), DrawScale(DrawingWand *,const double,const double), DrawSetClipPath(DrawingWand *,const char *), DrawSetClipRule(DrawingWand *,const FillRule), DrawSetClipUnits(DrawingWand *,const ClipPathUnits), DrawSetFillColor(DrawingWand *,const PixelWand *), DrawSetFillOpacity(DrawingWand *,const double), DrawSetFillRule(DrawingWand *,const FillRule), DrawSetFillPatternURL(DrawingWand *,const char *), DrawSetFont(DrawingWand *,const char *), DrawSetFontFamily(DrawingWand *,const char *), DrawSetFontSize(DrawingWand *,const double), DrawSetFontStretch(DrawingWand *,const StretchType), DrawSetFontStyle(DrawingWand *,const StyleType), DrawSetFontWeight(DrawingWand *,const unsigned long), DrawSetGravity(DrawingWand *,const GravityType), DrawSkewX(DrawingWand *,const double), DrawSkewY(DrawingWand *,const double), DrawSetStrokeAntialias(DrawingWand *,const unsigned int), DrawSetStrokeColor(DrawingWand *,const PixelWand *), DrawSetStrokeDashArray(DrawingWand *,const unsigned long,const double *), DrawSetStrokeDashOffset(DrawingWand *,const double dashoffset), DrawSetStrokeLineCap(DrawingWand *,const LineCap), DrawSetStrokeLineJoin(DrawingWand *,const LineJoin), DrawSetStrokeMiterLimit(DrawingWand *,const unsigned long), DrawSetStrokeOpacity(DrawingWand *, const double), DrawSetStrokePatternURL(DrawingWand *,const char *), DrawSetStrokeWidth(DrawingWand *,const double), DrawSetTextAntialias(DrawingWand *,const unsigned int), DrawSetTextDecoration(DrawingWand *,const DecorationType), DrawSetTextEncoding(DrawingWand *,const char *), DrawSetTextUnderColor(DrawingWand *,const PixelWand *), DrawSetViewbox(DrawingWand *,unsigned long,unsigned long,unsigned long, unsigned long), DrawTranslate(DrawingWand *,const double,const double); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/wand/magick_wand.h ================================================ /* Copyright (C) 2003-2019 GraphicsMagick Group */ /* ImageMagick MagickWand interface. */ #ifndef _MAGICK_WAND_H #define _MAGICK_WAND_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if defined(_VISUALC_) # if defined(_MT) && defined(_DLL) && !defined(_LIB) # pragma warning( disable: 4273 ) # if !defined(_WANDLIB_) # define WandExport __declspec(dllimport) # else # define WandExport __declspec(dllexport) # endif # else # define WandExport # endif # pragma warning(disable : 4018) # pragma warning(disable : 4244) # pragma warning(disable : 4142) #else # define WandExport #endif #include "magick/api.h" #include "wand/wand_symbols.h" #include "wand/drawing_wand.h" #include "wand/pixel_wand.h" /* ImageMagick compatibility definitions */ #define MagickSizeType magick_int64_t #define ReplaceCompositeOp CopyCompositeOp #define IndexChannel BlackChannel #define AreaResource UndefinedResource /* not supported */ extern WandExport int FormatMagickString(char *,const size_t,const char *,...) MAGICK_ATTRIBUTE((format (printf,3,4))); extern WandExport size_t CopyMagickString(char *,const char *,const size_t); typedef struct _MagickWand MagickWand; extern WandExport char *MagickDescribeImage(MagickWand *), *MagickGetConfigureInfo(MagickWand *,const char *) MAGICK_FUNC_CONST, *MagickGetException(const MagickWand *,ExceptionType *), *MagickGetFilename(const MagickWand *), *MagickGetImageAttribute(MagickWand *, const char *), *MagickGetImageFilename(MagickWand *), *MagickGetImageFormat(MagickWand *), *MagickGetImageSignature(MagickWand *), **MagickQueryFonts(const char *,unsigned long *), **MagickQueryFormats(const char *,unsigned long *); extern WandExport CompositeOperator MagickGetImageCompose(MagickWand *); extern WandExport ColorspaceType MagickGetImageColorspace(MagickWand *); extern WandExport CompressionType MagickGetImageCompression(MagickWand *); extern WandExport const char *MagickGetCopyright(void) MAGICK_FUNC_CONST, *MagickGetHomeURL(void) MAGICK_FUNC_CONST, *MagickGetImageGeometry(MagickWand *), *MagickGetPackageName(void) MAGICK_FUNC_CONST, *MagickGetQuantumDepth(unsigned long *), *MagickGetReleaseDate(void) MAGICK_FUNC_CONST, *MagickGetVersion(unsigned long *) MAGICK_FUNC_CONST; extern WandExport DisposeType MagickGetImageDispose(MagickWand *); extern WandExport double MagickGetImageGamma(MagickWand *), MagickGetImageFuzz(MagickWand *), *MagickGetSamplingFactors(MagickWand *,unsigned long *), *MagickQueryFontMetrics(MagickWand *,const DrawingWand *,const char *); extern WandExport GravityType MagickGetImageGravity(MagickWand *wand); extern WandExport ImageType MagickGetImageType(MagickWand *); extern WandExport ImageType MagickGetImageSavedType(MagickWand *) MAGICK_FUNC_CONST; extern WandExport InterlaceType MagickGetImageInterlaceScheme(MagickWand *); extern WandExport long MagickGetImageIndex(MagickWand *); extern WandExport MagickSizeType MagickGetImageSize(MagickWand *); extern WandExport MagickWand *CloneMagickWand(const MagickWand *), *MagickAppendImages(MagickWand *,const unsigned int), *MagickAverageImages(MagickWand *), *MagickCoalesceImages(MagickWand *), *MagickCompareImageChannels(MagickWand *,const MagickWand *,const ChannelType, const MetricType,double *), *MagickCompareImages(MagickWand *,const MagickWand *,const MetricType, double *), *MagickDeconstructImages(MagickWand *), *MagickFlattenImages(MagickWand *), *MagickFxImage(MagickWand *,const char *), *MagickFxImageChannel(MagickWand *,const ChannelType,const char *), *MagickGetImage(MagickWand *), *MagickMorphImages(MagickWand *,const unsigned long), *MagickMosaicImages(MagickWand *), *MagickMontageImage(MagickWand *,const DrawingWand *,const char *, const char *,const MontageMode,const char *), *MagickPreviewImages(MagickWand *wand,const PreviewType), *MagickSteganoImage(MagickWand *,const MagickWand *,const long), *MagickStereoImage(MagickWand *,const MagickWand *), *MagickTextureImage(MagickWand *,const MagickWand *), *MagickTransformImage(MagickWand *,const char *,const char *), *NewMagickWand(void); extern WandExport OrientationType MagickGetImageOrientation(MagickWand *); extern WandExport PixelWand **MagickGetImageHistogram(MagickWand *,unsigned long *); extern WandExport RenderingIntent MagickGetImageRenderingIntent(MagickWand *); extern WandExport ResolutionType MagickGetImageUnits(MagickWand *); extern WandExport unsigned int DestroyMagickWand(MagickWand *), MagickAdaptiveThresholdImage(MagickWand *,const unsigned long, const unsigned long,const long), MagickAddImage(MagickWand *,const MagickWand *), MagickAddNoiseImage(MagickWand *,const NoiseType), MagickAffineTransformImage(MagickWand *,const DrawingWand *), MagickAnnotateImage(MagickWand *,const DrawingWand *,const double, const double,const double,const char *), MagickAnimateImages(MagickWand *,const char *), MagickAutoOrientImage(MagickWand *wand,const OrientationType), MagickBlackThresholdImage(MagickWand *,const PixelWand *), MagickBlurImage(MagickWand *,const double,const double), MagickBorderImage(MagickWand *,const PixelWand *,const unsigned long, const unsigned long), MagickCdlImage(MagickWand *wand,const char *cdl), MagickCharcoalImage(MagickWand *,const double,const double), MagickChopImage(MagickWand *,const unsigned long,const unsigned long, const long,const long), MagickClipImage(MagickWand *), MagickClipPathImage(MagickWand *,const char *,const unsigned int), MagickColorFloodfillImage(MagickWand *,const PixelWand *,const double, const PixelWand *,const long,const long), MagickColorizeImage(MagickWand *,const PixelWand *,const PixelWand *), MagickCommentImage(MagickWand *,const char *), MagickCompositeImage(MagickWand *,const MagickWand *,const CompositeOperator, const long,const long), MagickContrastImage(MagickWand *,const unsigned int), MagickConvolveImage(MagickWand *,const unsigned long,const double *), MagickCropImage(MagickWand *,const unsigned long,const unsigned long, const long,const long), MagickCycleColormapImage(MagickWand *,const long), MagickDespeckleImage(MagickWand *), MagickDisplayImage(MagickWand *,const char *), MagickDisplayImages(MagickWand *,const char *), MagickDrawImage(MagickWand *,const DrawingWand *), MagickEdgeImage(MagickWand *,const double), MagickEmbossImage(MagickWand *,const double,const double), MagickEnhanceImage(MagickWand *), MagickEqualizeImage(MagickWand *), MagickExtentImage(MagickWand *,const size_t,const size_t,const ssize_t, const ssize_t), MagickFlipImage(MagickWand *), MagickFlopImage(MagickWand *), MagickFrameImage(MagickWand *,const PixelWand *,const unsigned long, const unsigned long,const long,const long), MagickGammaImage(MagickWand *,const double), MagickGammaImageChannel(MagickWand *,const ChannelType,const double), MagickGetImageBackgroundColor(MagickWand *,PixelWand *), MagickGetImageBluePrimary(MagickWand *,double *,double *), MagickGetImageBorderColor(MagickWand *,PixelWand *), MagickGetImageBoundingBox(MagickWand *wand,const double fuzz, unsigned long *width,unsigned long *height,long *x, long *y), MagickGetImageChannelExtrema(MagickWand *,const ChannelType,unsigned long *, unsigned long *), MagickGetImageChannelMean(MagickWand *,const ChannelType,double *,double *), MagickGetImageColormapColor(MagickWand *,const unsigned long,PixelWand *), MagickGetImageExtrema(MagickWand *,unsigned long *,unsigned long *), MagickGetImageGreenPrimary(MagickWand *,double *,double *), MagickGetImageMatte(MagickWand *), MagickGetImageMatteColor(MagickWand *,PixelWand *), MagickGetImagePage(MagickWand *wand, unsigned long *width,unsigned long *height,long *x,long *y), MagickGetImagePixels(MagickWand *,const long,const long,const unsigned long, const unsigned long,const char *,const StorageType,unsigned char *), MagickGetImageRedPrimary(MagickWand *,double *,double *), MagickGetImageResolution(MagickWand *,double *,double *), MagickGetImageWhitePoint(MagickWand *,double *,double *), MagickGetSize(const MagickWand *,unsigned long *,unsigned long *), MagickHaldClutImage(MagickWand *wand,const MagickWand *clut_wand), MagickHasColormap(MagickWand *,unsigned int *), MagickHasNextImage(MagickWand *), MagickHasPreviousImage(MagickWand *), MagickImplodeImage(MagickWand *,const double), MagickIsGrayImage(MagickWand *,unsigned int *), MagickIsMonochromeImage(MagickWand *,unsigned int *), MagickIsOpaqueImage(MagickWand *,unsigned int *), MagickIsPaletteImage(MagickWand *,unsigned int *), MagickLabelImage(MagickWand *,const char *), MagickLevelImage(MagickWand *,const double,const double,const double), MagickLevelImageChannel(MagickWand *,const ChannelType,const double, const double,const double), MagickMagnifyImage(MagickWand *), MagickMapImage(MagickWand *,const MagickWand *,const unsigned int), MagickMatteFloodfillImage(MagickWand *,const Quantum,const double, const PixelWand *,const long,const long), MagickMedianFilterImage(MagickWand *,const double), MagickMinifyImage(MagickWand *), MagickModulateImage(MagickWand *,const double,const double,const double), MagickMotionBlurImage(MagickWand *,const double,const double,const double), MagickNegateImage(MagickWand *,const unsigned int), MagickNegateImageChannel(MagickWand *,const ChannelType,const unsigned int), MagickNextImage(MagickWand *), MagickNormalizeImage(MagickWand *), MagickOilPaintImage(MagickWand *,const double), MagickOpaqueImage(MagickWand *,const PixelWand *,const PixelWand *, const double), MagickOperatorImageChannel(MagickWand *,const ChannelType,const QuantumOperator, const double), MagickPingImage(MagickWand *,const char *), MagickPreviousImage(MagickWand *), MagickProfileImage(MagickWand *,const char *,const unsigned char *, const unsigned long), MagickQuantizeImage(MagickWand *,const unsigned long,const ColorspaceType, const unsigned long,const unsigned int,const unsigned int), MagickQuantizeImages(MagickWand *,const unsigned long,const ColorspaceType, const unsigned long,const unsigned int,const unsigned int), MagickRadialBlurImage(MagickWand *,const double), MagickRaiseImage(MagickWand *,const unsigned long,const unsigned long, const long,const long,const unsigned int), MagickReadImage(MagickWand *,const char *), MagickReadImageBlob(MagickWand *,const unsigned char *,const size_t length), MagickReadImageFile(MagickWand *,FILE *), MagickReduceNoiseImage(MagickWand *,const double), MagickRelinquishMemory(void *), MagickRemoveImage(MagickWand *), MagickRemoveImageOption(MagickWand *wand,const char *,const char *), MagickResampleImage(MagickWand *,const double,const double,const FilterTypes, const double), MagickResizeImage(MagickWand *,const unsigned long,const unsigned long, const FilterTypes,const double), MagickRollImage(MagickWand *,const long,const long), MagickRotateImage(MagickWand *,const PixelWand *,const double), MagickSampleImage(MagickWand *,const unsigned long,const unsigned long), MagickScaleImage(MagickWand *,const unsigned long,const unsigned long), MagickSeparateImageChannel(MagickWand *,const ChannelType), MagickSetCompressionQuality(MagickWand *wand,const unsigned long quality), MagickSetFilename(MagickWand *,const char *), MagickSetFormat(MagickWand *,const char *), MagickSetImage(MagickWand *,const MagickWand *), MagickSetImageAttribute(MagickWand *,const char *, const char *), MagickSetImageBackgroundColor(MagickWand *,const PixelWand *), MagickSetImageBluePrimary(MagickWand *,const double,const double), MagickSetImageBorderColor(MagickWand *,const PixelWand *), MagickSetImageChannelDepth(MagickWand *,const ChannelType, const unsigned long), MagickSetImageColormapColor(MagickWand *,const unsigned long, const PixelWand *), MagickSetImageCompose(MagickWand *,const CompositeOperator), MagickSetImageCompression(MagickWand *,const CompressionType), MagickSetImageDelay(MagickWand *,const unsigned long), MagickSetImageDepth(MagickWand *,const unsigned long), MagickSetImageDispose(MagickWand *,const DisposeType), MagickSetImageColorspace(MagickWand *,const ColorspaceType), MagickSetImageGreenPrimary(MagickWand *,const double,const double), MagickSetImageGamma(MagickWand *,const double), MagickSetImageGeometry(MagickWand *,const char *), MagickSetImageGravity(MagickWand *,const GravityType), MagickSetImageFilename(MagickWand *,const char *), MagickSetImageFormat(MagickWand *wand,const char *format), MagickSetImageFuzz(MagickWand *,const double), MagickSetImageIndex(MagickWand *,const long), MagickSetImageInterlaceScheme(MagickWand *,const InterlaceType), MagickSetImageIterations(MagickWand *,const unsigned long), MagickSetImageMatte(MagickWand *,const unsigned int), MagickSetImageMatteColor(MagickWand *,const PixelWand *), MagickSetImageOption(MagickWand *,const char *,const char *,const char *), MagickSetImageOrientation(MagickWand *,const OrientationType), MagickSetImagePage(MagickWand *wand, const unsigned long width,const unsigned long height,const long x, const long y), MagickSetImagePixels(MagickWand *,const long,const long,const unsigned long, const unsigned long,const char *,const StorageType,unsigned char *), MagickSetImageRedPrimary(MagickWand *,const double,const double), MagickSetImageRenderingIntent(MagickWand *,const RenderingIntent), MagickSetImageResolution(MagickWand *,const double,const double), MagickSetImageScene(MagickWand *,const unsigned long), MagickSetImageType(MagickWand *,const ImageType), MagickSetImageSavedType(MagickWand *,const ImageType), MagickSetImageUnits(MagickWand *,const ResolutionType), MagickSetImageVirtualPixelMethod(MagickWand *,const VirtualPixelMethod), MagickSetPassphrase(MagickWand *,const char *), MagickSetImageProfile(MagickWand *,const char *,const unsigned char *, const unsigned long), MagickSetResolution(MagickWand *wand, const double x_resolution,const double y_resolution), MagickSetResolutionUnits(MagickWand *wand,const ResolutionType units), MagickSetResourceLimit(const ResourceType type,const unsigned long limit), MagickSetSamplingFactors(MagickWand *,const unsigned long,const double *), MagickSetSize(MagickWand *,const unsigned long,const unsigned long), MagickSetImageWhitePoint(MagickWand *,const double,const double), MagickSetInterlaceScheme(MagickWand *,const InterlaceType), MagickSharpenImage(MagickWand *,const double,const double), MagickShaveImage(MagickWand *,const unsigned long,const unsigned long), MagickShearImage(MagickWand *,const PixelWand *,const double,const double), MagickSolarizeImage(MagickWand *,const double), MagickSpreadImage(MagickWand *,const double), MagickStripImage(MagickWand *), MagickSwirlImage(MagickWand *,const double), MagickTintImage(MagickWand *,const PixelWand *,const PixelWand *), MagickThresholdImage(MagickWand *,const double), MagickThresholdImageChannel(MagickWand *,const ChannelType,const double), MagickTransparentImage(MagickWand *,const PixelWand *,const Quantum, const double), MagickTrimImage(MagickWand *,const double), MagickUnsharpMaskImage(MagickWand *,const double,const double,const double, const double), MagickWaveImage(MagickWand *,const double,const double), MagickWhiteThresholdImage(MagickWand *,const PixelWand *), MagickWriteImage(MagickWand *,const char *), MagickWriteImageFile(MagickWand *,FILE *), MagickWriteImagesFile(MagickWand *,FILE *,const unsigned int), MagickWriteImages(MagickWand *,const char *,const unsigned int); extern WandExport unsigned long MagickGetImageColors(MagickWand *), MagickGetImageDelay(MagickWand *), MagickGetImageChannelDepth(MagickWand *,const ChannelType), MagickGetImageDepth(MagickWand *), MagickGetImageHeight(MagickWand *), MagickGetImageIterations(MagickWand *), MagickGetImageScene(MagickWand *), MagickGetImageWidth(MagickWand *), MagickGetNumberImages(MagickWand *), MagickGetResourceLimit(const ResourceType); extern WandExport VirtualPixelMethod MagickGetImageVirtualPixelMethod(MagickWand *); extern WandExport unsigned char *MagickGetImageProfile(MagickWand *,const char *,unsigned long *), *MagickRemoveImageProfile(MagickWand *,const char *,unsigned long *), *MagickWriteImageBlob(MagickWand *,size_t *); extern WandExport void MagickClearException(MagickWand *), MagickResetIterator(MagickWand *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/wand/pixel_wand.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group Copyright (C) 2003 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Pixel Wand Methods. */ #ifndef _MAGICK_PIXEL_WAND_H #define _MAGICK_PIXEL_WAND_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "wand/wand_symbols.h" typedef struct _PixelWand PixelWand; extern WandExport char *PixelGetColorAsString(const PixelWand *); extern WandExport double PixelGetBlack(const PixelWand *) MAGICK_FUNC_PURE, PixelGetBlue(const PixelWand *) MAGICK_FUNC_PURE, PixelGetCyan(const PixelWand *) MAGICK_FUNC_PURE, PixelGetGreen(const PixelWand *) MAGICK_FUNC_PURE, PixelGetMagenta(const PixelWand *) MAGICK_FUNC_PURE, PixelGetOpacity(const PixelWand *) MAGICK_FUNC_PURE, PixelGetRed(const PixelWand *) MAGICK_FUNC_PURE, PixelGetYellow(const PixelWand *) MAGICK_FUNC_PURE; extern WandExport PixelWand *ClonePixelWand(const PixelWand *), **ClonePixelWands(const PixelWand **,const unsigned long), *NewPixelWand(void), **NewPixelWands(const unsigned long); extern WandExport Quantum PixelGetBlackQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetBlueQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetCyanQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetGreenQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetMagentaQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetOpacityQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetRedQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetYellowQuantum(const PixelWand *) MAGICK_FUNC_PURE; extern WandExport unsigned int PixelSetColor(PixelWand *,const char *); extern WandExport unsigned long PixelGetColorCount(const PixelWand *) MAGICK_FUNC_PURE; extern WandExport void DestroyPixelWand(PixelWand *), PixelGetQuantumColor(const PixelWand *,PixelPacket *), PixelSetBlack(PixelWand *,const double), PixelSetBlackQuantum(PixelWand *,const Quantum), PixelSetBlue(PixelWand *,const double), PixelSetBlueQuantum(PixelWand *,const Quantum), PixelSetColorCount(PixelWand *,const unsigned long), PixelSetCyan(PixelWand *,const double), PixelSetCyanQuantum(PixelWand *,const Quantum), PixelSetGreen(PixelWand *,const double), PixelSetGreenQuantum(PixelWand *,const Quantum), PixelSetMagenta(PixelWand *,const double), PixelSetMagentaQuantum(PixelWand *,const Quantum), PixelSetOpacity(PixelWand *,const double), PixelSetOpacityQuantum(PixelWand *,const Quantum), PixelSetQuantumColor(PixelWand *,PixelPacket *), PixelSetRed(PixelWand *,const double), PixelSetRedQuantum(PixelWand *,const Quantum), PixelSetYellow(PixelWand *,const double), PixelSetYellowQuantum(PixelWand *,const Quantum); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/wand/wand_api.h ================================================ /* Copyright (C) 2003-2018 GraphicsMagick Group GraphicsMagick Wand API Methods */ #ifndef _MAGICK_WAND_API_H #define _MAGICK_WAND_API_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include #include #if defined(_VISUALC_) /** * Under VISUALC we have single threaded static libraries, or * mutli-threaded DLLs using the multithreaded runtime DLLs. **/ # if defined(_MT) && defined(_DLL) && !defined(_LIB) # pragma warning( disable: 4273 ) /* Disable the stupid dll linkage warnings */ # if !defined(_WANDLIB_) # define WandExport __declspec(dllimport) # else # define WandExport __declspec(dllexport) # endif # else # define WandExport # endif # pragma warning(disable : 4018) # pragma warning(disable : 4244) # pragma warning(disable : 4142) #else # define WandExport #endif #include #include #include #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_WAND_API_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/GraphicsMagick/wand/wand_symbols.h ================================================ /* Copyright (C) 2012-2018 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Library symbol name-scoping support. */ #if !defined(_MAGICK_WAND_SYMBOLS_H) #define _MAGICK_WAND_SYMBOLS_H #if defined(PREFIX_MAGICK_SYMBOLS) #define CloneMagickWand GmCloneMagickWand #define ClonePixelWand GmClonePixelWand #define ClonePixelWands GmClonePixelWands #define CopyMagickString GmCopyMagickString #define DestroyMagickWand GmDestroyMagickWand #define DestroyPixelWand GmDestroyPixelWand #define FormatMagickString GmFormatMagickString #define FormatMagickStringList GmFormatMagickStringList #define MagickAdaptiveThresholdImage GmMagickAdaptiveThresholdImage #define MagickAddImage GmMagickAddImage #define MagickAddNoiseImage GmMagickAddNoiseImage #define MagickAffineTransformImage GmMagickAffineTransformImage #define MagickAnimateImages GmMagickAnimateImages #define MagickAnnotateImage GmMagickAnnotateImage #define MagickAppendImages GmMagickAppendImages #define MagickAutoOrientImage GmMagickAutoOrientImage #define MagickAverageImages GmMagickAverageImages #define MagickBlackThresholdImage GmMagickBlackThresholdImage #define MagickBlurImage GmMagickBlurImage #define MagickBorderImage GmMagickBorderImage #define MagickCdlImage GmMagickCdlImage #define MagickCharcoalImage GmMagickCharcoalImage #define MagickChopImage GmMagickChopImage #define MagickClearException GmMagickClearException #define MagickClipImage GmMagickClipImage #define MagickClipPathImage GmMagickClipPathImage #define MagickCloneDrawingWand GmMagickCloneDrawingWand #define MagickCoalesceImages GmMagickCoalesceImages #define MagickColorFloodfillImage GmMagickColorFloodfillImage #define MagickColorizeImage GmMagickColorizeImage #define MagickCommentImage GmMagickCommentImage #define MagickCompareImageChannels GmMagickCompareImageChannels #define MagickCompareImages GmMagickCompareImages #define MagickCompositeImage GmMagickCompositeImage #define MagickContrastImage GmMagickContrastImage #define MagickConvolveImage GmMagickConvolveImage #define MagickCropImage GmMagickCropImage #define MagickCycleColormapImage GmMagickCycleColormapImage #define MagickDeconstructImages GmMagickDeconstructImages #define MagickDescribeImage GmMagickDescribeImage #define MagickDespeckleImage GmMagickDespeckleImage #define MagickDestroyDrawingWand GmMagickDestroyDrawingWand #define MagickDisplayImage GmMagickDisplayImage #define MagickDisplayImages GmMagickDisplayImages #define MagickDrawAffine GmMagickDrawAffine #define MagickDrawAllocateWand GmMagickDrawAllocateWand #define MagickDrawAnnotation GmMagickDrawAnnotation #define MagickDrawArc GmMagickDrawArc #define MagickDrawBezier GmMagickDrawBezier #define MagickDrawCircle GmMagickDrawCircle #define MagickDrawClearException GmMagickDrawClearException #define MagickDrawColor GmMagickDrawColor #define MagickDrawComment GmMagickDrawComment #define MagickDrawComposite GmMagickDrawComposite #define MagickDrawEllipse GmMagickDrawEllipse #define MagickDrawGetClipPath GmMagickDrawGetClipPath #define MagickDrawGetClipRule GmMagickDrawGetClipRule #define MagickDrawGetClipUnits GmMagickDrawGetClipUnits #define MagickDrawGetException GmMagickDrawGetException #define MagickDrawGetFillColor GmMagickDrawGetFillColor #define MagickDrawGetFillOpacity GmMagickDrawGetFillOpacity #define MagickDrawGetFillRule GmMagickDrawGetFillRule #define MagickDrawGetFont GmMagickDrawGetFont #define MagickDrawGetFontFamily GmMagickDrawGetFontFamily #define MagickDrawGetFontSize GmMagickDrawGetFontSize #define MagickDrawGetFontStretch GmMagickDrawGetFontStretch #define MagickDrawGetFontStyle GmMagickDrawGetFontStyle #define MagickDrawGetFontWeight GmMagickDrawGetFontWeight #define MagickDrawGetGravity GmMagickDrawGetGravity #define MagickDrawGetStrokeAntialias GmMagickDrawGetStrokeAntialias #define MagickDrawGetStrokeColor GmMagickDrawGetStrokeColor #define MagickDrawGetStrokeDashArray GmMagickDrawGetStrokeDashArray #define MagickDrawGetStrokeDashOffset GmMagickDrawGetStrokeDashOffset #define MagickDrawGetStrokeLineCap GmMagickDrawGetStrokeLineCap #define MagickDrawGetStrokeLineJoin GmMagickDrawGetStrokeLineJoin #define MagickDrawGetStrokeMiterLimit GmMagickDrawGetStrokeMiterLimit #define MagickDrawGetStrokeOpacity GmMagickDrawGetStrokeOpacity #define MagickDrawGetStrokeWidth GmMagickDrawGetStrokeWidth #define MagickDrawGetTextAntialias GmMagickDrawGetTextAntialias #define MagickDrawGetTextDecoration GmMagickDrawGetTextDecoration #define MagickDrawGetTextEncoding GmMagickDrawGetTextEncoding #define MagickDrawGetTextUnderColor GmMagickDrawGetTextUnderColor #define MagickDrawImage GmMagickDrawImage #define MagickDrawLine GmMagickDrawLine #define MagickDrawMatte GmMagickDrawMatte #define MagickDrawPathClose GmMagickDrawPathClose #define MagickDrawPathCurveToAbsolute GmMagickDrawPathCurveToAbsolute #define MagickDrawPathCurveToQuadraticBezierAbsolute GmMagickDrawPathCurveToQuadraticBezierAbsolute #define MagickDrawPathCurveToQuadraticBezierRelative GmMagickDrawPathCurveToQuadraticBezierRelative #define MagickDrawPathCurveToQuadraticBezierSmoothAbsolute GmMagickDrawPathCurveToQuadraticBezierSmoothAbsolute #define MagickDrawPathCurveToQuadraticBezierSmoothRelative GmMagickDrawPathCurveToQuadraticBezierSmoothRelative #define MagickDrawPathCurveToRelative GmMagickDrawPathCurveToRelative #define MagickDrawPathCurveToSmoothAbsolute GmMagickDrawPathCurveToSmoothAbsolute #define MagickDrawPathCurveToSmoothRelative GmMagickDrawPathCurveToSmoothRelative #define MagickDrawPathEllipticArcAbsolute GmMagickDrawPathEllipticArcAbsolute #define MagickDrawPathEllipticArcRelative GmMagickDrawPathEllipticArcRelative #define MagickDrawPathFinish GmMagickDrawPathFinish #define MagickDrawPathLineToAbsolute GmMagickDrawPathLineToAbsolute #define MagickDrawPathLineToHorizontalAbsolute GmMagickDrawPathLineToHorizontalAbsolute #define MagickDrawPathLineToHorizontalRelative GmMagickDrawPathLineToHorizontalRelative #define MagickDrawPathLineToRelative GmMagickDrawPathLineToRelative #define MagickDrawPathLineToVerticalAbsolute GmMagickDrawPathLineToVerticalAbsolute #define MagickDrawPathLineToVerticalRelative GmMagickDrawPathLineToVerticalRelative #define MagickDrawPathMoveToAbsolute GmMagickDrawPathMoveToAbsolute #define MagickDrawPathMoveToRelative GmMagickDrawPathMoveToRelative #define MagickDrawPathStart GmMagickDrawPathStart #define MagickDrawPeekGraphicContext GmMagickDrawPeekGraphicContext #define MagickDrawPoint GmMagickDrawPoint #define MagickDrawPolygon GmMagickDrawPolygon #define MagickDrawPolyline GmMagickDrawPolyline #define MagickDrawPopClipPath GmMagickDrawPopClipPath #define MagickDrawPopDefs GmMagickDrawPopDefs #define MagickDrawPopGraphicContext GmMagickDrawPopGraphicContext #define MagickDrawPopPattern GmMagickDrawPopPattern #define MagickDrawPushClipPath GmMagickDrawPushClipPath #define MagickDrawPushDefs GmMagickDrawPushDefs #define MagickDrawPushGraphicContext GmMagickDrawPushGraphicContext #define MagickDrawPushPattern GmMagickDrawPushPattern #define MagickDrawRectangle GmMagickDrawRectangle #define MagickDrawRender GmMagickDrawRender #define MagickDrawRotate GmMagickDrawRotate #define MagickDrawRoundRectangle GmMagickDrawRoundRectangle #define MagickDrawScale GmMagickDrawScale #define MagickDrawSetClipPath GmMagickDrawSetClipPath #define MagickDrawSetClipRule GmMagickDrawSetClipRule #define MagickDrawSetClipUnits GmMagickDrawSetClipUnits #define MagickDrawSetFillColor GmMagickDrawSetFillColor #define MagickDrawSetFillOpacity GmMagickDrawSetFillOpacity #define MagickDrawSetFillPatternURL GmMagickDrawSetFillPatternURL #define MagickDrawSetFillRule GmMagickDrawSetFillRule #define MagickDrawSetFont GmMagickDrawSetFont #define MagickDrawSetFontFamily GmMagickDrawSetFontFamily #define MagickDrawSetFontSize GmMagickDrawSetFontSize #define MagickDrawSetFontStretch GmMagickDrawSetFontStretch #define MagickDrawSetFontStyle GmMagickDrawSetFontStyle #define MagickDrawSetFontWeight GmMagickDrawSetFontWeight #define MagickDrawSetGravity GmMagickDrawSetGravity #define MagickDrawSetStrokeAntialias GmMagickDrawSetStrokeAntialias #define MagickDrawSetStrokeColor GmMagickDrawSetStrokeColor #define MagickDrawSetStrokeDashArray GmMagickDrawSetStrokeDashArray #define MagickDrawSetStrokeDashOffset GmMagickDrawSetStrokeDashOffset #define MagickDrawSetStrokeLineCap GmMagickDrawSetStrokeLineCap #define MagickDrawSetStrokeLineJoin GmMagickDrawSetStrokeLineJoin #define MagickDrawSetStrokeMiterLimit GmMagickDrawSetStrokeMiterLimit #define MagickDrawSetStrokeOpacity GmMagickDrawSetStrokeOpacity #define MagickDrawSetStrokePatternURL GmMagickDrawSetStrokePatternURL #define MagickDrawSetStrokeWidth GmMagickDrawSetStrokeWidth #define MagickDrawSetTextAntialias GmMagickDrawSetTextAntialias #define MagickDrawSetTextDecoration GmMagickDrawSetTextDecoration #define MagickDrawSetTextEncoding GmMagickDrawSetTextEncoding #define MagickDrawSetTextUnderColor GmMagickDrawSetTextUnderColor #define MagickDrawSetViewbox GmMagickDrawSetViewbox #define MagickDrawSkewX GmMagickDrawSkewX #define MagickDrawSkewY GmMagickDrawSkewY #define MagickDrawTranslate GmMagickDrawTranslate #define MagickEdgeImage GmMagickEdgeImage #define MagickEmbossImage GmMagickEmbossImage #define MagickEnhanceImage GmMagickEnhanceImage #define MagickEqualizeImage GmMagickEqualizeImage #define MagickExtentImage GmMagickExtentImage #define MagickFlattenImages GmMagickFlattenImages #define MagickFlipImage GmMagickFlipImage #define MagickFlopImage GmMagickFlopImage #define MagickFrameImage GmMagickFrameImage #define MagickFxImage GmMagickFxImage #define MagickFxImageChannel GmMagickFxImageChannel #define MagickGammaImage GmMagickGammaImage #define MagickGammaImageChannel GmMagickGammaImageChannel #define MagickGetConfigureInfo GmMagickGetConfigureInfo #define MagickGetCopyright GmMagickGetCopyright #define MagickGetException GmMagickGetException #define MagickGetFilename GmMagickGetFilename #define MagickGetHomeURL GmMagickGetHomeURL #define MagickGetImage GmMagickGetImage #define MagickGetImageAttribute GmMagickGetImageAttribute #define MagickGetImageBackgroundColor GmMagickGetImageBackgroundColor #define MagickGetImageBluePrimary GmMagickGetImageBluePrimary #define MagickGetImageBorderColor GmMagickGetImageBorderColor #define MagickGetImageBoundingBox GmMagickGetImageBoundingBox #define MagickGetImageChannelDepth GmMagickGetImageChannelDepth #define MagickGetImageChannelExtrema GmMagickGetImageChannelExtrema #define MagickGetImageChannelMean GmMagickGetImageChannelMean #define MagickGetImageColormapColor GmMagickGetImageColormapColor #define MagickGetImageColors GmMagickGetImageColors #define MagickGetImageColorspace GmMagickGetImageColorspace #define MagickGetImageCompose GmMagickGetImageCompose #define MagickGetImageCompression GmMagickGetImageCompression #define MagickGetImageDelay GmMagickGetImageDelay #define MagickGetImageDepth GmMagickGetImageDepth #define MagickGetImageDispose GmMagickGetImageDispose #define MagickGetImageExtrema GmMagickGetImageExtrema #define MagickGetImageFilename GmMagickGetImageFilename #define MagickGetImageFormat GmMagickGetImageFormat #define MagickGetImageFuzz GmMagickGetImageFuzz #define MagickGetImageGamma GmMagickGetImageGamma #define MagickGetImageGeometry GmMagickGetImageGeometry #define MagickGetImageGravity GmMagickGetImageGravity #define MagickGetImageGreenPrimary GmMagickGetImageGreenPrimary #define MagickGetImageHeight GmMagickGetImageHeight #define MagickGetImageHistogram GmMagickGetImageHistogram #define MagickGetImageIndex GmMagickGetImageIndex #define MagickGetImageInterlaceScheme GmMagickGetImageInterlaceScheme #define MagickGetImageIterations GmMagickGetImageIterations #define MagickGetImageMatte GmMagickGetImageMatte #define MagickGetImageMatteColor GmMagickGetImageMatteColor #define MagickGetImageOrientation GmMagickGetImageOrientation #define MagickGetImagePage GmMagickGetImagePage #define MagickGetImagePixels GmMagickGetImagePixels #define MagickGetImageProfile GmMagickGetImageProfile #define MagickGetImageRedPrimary GmMagickGetImageRedPrimary #define MagickGetImageRenderingIntent GmMagickGetImageRenderingIntent #define MagickGetImageResolution GmMagickGetImageResolution #define MagickGetImageSavedType GmMagickGetImageSavedType #define MagickGetImageScene GmMagickGetImageScene #define MagickGetImageSignature GmMagickGetImageSignature #define MagickGetImageSize GmMagickGetImageSize #define MagickGetImageType GmMagickGetImageType #define MagickGetImageUnits GmMagickGetImageUnits #define MagickGetImageVirtualPixelMethod GmMagickGetImageVirtualPixelMethod #define MagickGetImageWhitePoint GmMagickGetImageWhitePoint #define MagickGetImageWidth GmMagickGetImageWidth #define MagickGetNumberImages GmMagickGetNumberImages #define MagickGetPackageName GmMagickGetPackageName #define MagickGetQuantumDepth GmMagickGetQuantumDepth #define MagickGetReleaseDate GmMagickGetReleaseDate #define MagickGetResourceLimit GmMagickGetResourceLimit #define MagickGetSamplingFactors GmMagickGetSamplingFactors #define MagickGetSize GmMagickGetSize #define MagickGetVersion GmMagickGetVersion #define MagickHaldClutImage GmMagickHaldClutImage #define MagickHasColormap GmMagickHasColormap #define MagickHasNextImage GmMagickHasNextImage #define MagickHasPreviousImage GmMagickHasPreviousImage #define MagickImplodeImage GmMagickImplodeImage #define MagickIsGrayImage GmMagickIsGrayImage #define MagickIsMonochromeImage GmMagickIsMonochromeImage #define MagickIsOpaqueImage GmMagickIsOpaqueImage #define MagickIsPaletteImage GmMagickIsPaletteImage #define MagickLabelImage GmMagickLabelImage #define MagickLevelImage GmMagickLevelImage #define MagickLevelImageChannel GmMagickLevelImageChannel #define MagickMagnifyImage GmMagickMagnifyImage #define MagickMapImage GmMagickMapImage #define MagickMatteFloodfillImage GmMagickMatteFloodfillImage #define MagickMedianFilterImage GmMagickMedianFilterImage #define MagickMinifyImage GmMagickMinifyImage #define MagickModulateImage GmMagickModulateImage #define MagickMontageImage GmMagickMontageImage #define MagickMorphImages GmMagickMorphImages #define MagickMosaicImages GmMagickMosaicImages #define MagickMotionBlurImage GmMagickMotionBlurImage #define MagickNegateImage GmMagickNegateImage #define MagickNegateImageChannel GmMagickNegateImageChannel #define MagickNewDrawingWand GmMagickNewDrawingWand #define MagickNextImage GmMagickNextImage #define MagickNormalizeImage GmMagickNormalizeImage #define MagickOilPaintImage GmMagickOilPaintImage #define MagickOpaqueImage GmMagickOpaqueImage #define MagickOperatorImageChannel GmMagickOperatorImageChannel #define MagickPingImage GmMagickPingImage #define MagickPreviewImages GmMagickPreviewImages #define MagickPreviousImage GmMagickPreviousImage #define MagickProfileImage GmMagickProfileImage #define MagickQuantizeImage GmMagickQuantizeImage #define MagickQuantizeImages GmMagickQuantizeImages #define MagickQueryFontMetrics GmMagickQueryFontMetrics #define MagickQueryFonts GmMagickQueryFonts #define MagickQueryFormats GmMagickQueryFormats #define MagickRadialBlurImage GmMagickRadialBlurImage #define MagickRaiseImage GmMagickRaiseImage #define MagickReadImage GmMagickReadImage #define MagickReadImageBlob GmMagickReadImageBlob #define MagickReadImageFile GmMagickReadImageFile #define MagickReduceNoiseImage GmMagickReduceNoiseImage #define MagickRelinquishMemory GmMagickRelinquishMemory #define MagickRemoveImage GmMagickRemoveImage #define MagickRemoveImageOption GmMagickRemoveImageOption #define MagickRemoveImageProfile GmMagickRemoveImageProfile #define MagickResampleImage GmMagickResampleImage #define MagickResetIterator GmMagickResetIterator #define MagickResizeImage GmMagickResizeImage #define MagickRollImage GmMagickRollImage #define MagickRotateImage GmMagickRotateImage #define MagickSampleImage GmMagickSampleImage #define MagickScaleImage GmMagickScaleImage #define MagickSeparateImageChannel GmMagickSeparateImageChannel #define MagickSetCompressionQuality GmMagickSetCompressionQuality #define MagickSetDepth GmMagickSetDepth #define MagickSetFilename GmMagickSetFilename #define MagickSetFormat GmMagickSetFormat #define MagickSetImage GmMagickSetImage #define MagickSetImageAttribute GmMagickSetImageAttribute #define MagickSetImageBackgroundColor GmMagickSetImageBackgroundColor #define MagickSetImageBluePrimary GmMagickSetImageBluePrimary #define MagickSetImageBorderColor GmMagickSetImageBorderColor #define MagickSetImageChannelDepth GmMagickSetImageChannelDepth #define MagickSetImageColormapColor GmMagickSetImageColormapColor #define MagickSetImageColorspace GmMagickSetImageColorspace #define MagickSetImageCompose GmMagickSetImageCompose #define MagickSetImageCompression GmMagickSetImageCompression #define MagickSetImageDelay GmMagickSetImageDelay #define MagickSetImageDepth GmMagickSetImageDepth #define MagickSetImageDispose GmMagickSetImageDispose #define MagickSetImageFilename GmMagickSetImageFilename #define MagickSetImageFormat GmMagickSetImageFormat #define MagickSetImageFuzz GmMagickSetImageFuzz #define MagickSetImageGamma GmMagickSetImageGamma #define MagickSetImageGeometry GmMagickSetImageGeometry #define MagickSetImageGravity GmMagickSetImageGravity #define MagickSetImageGreenPrimary GmMagickSetImageGreenPrimary #define MagickSetImageIndex GmMagickSetImageIndex #define MagickSetImageInterlaceScheme GmMagickSetImageInterlaceScheme #define MagickSetImageIterations GmMagickSetImageIterations #define MagickSetImageMatte GmMagickSetImageMatte #define MagickSetImageMatteColor GmMagickSetImageMatteColor #define MagickSetImageOption GmMagickSetImageOption #define MagickSetImageOrientation GmMagickSetImageOrientation #define MagickSetImagePage GmMagickSetImagePage #define MagickSetImagePixels GmMagickSetImagePixels #define MagickSetImageProfile GmMagickSetImageProfile #define MagickSetImageRedPrimary GmMagickSetImageRedPrimary #define MagickSetImageRenderingIntent GmMagickSetImageRenderingIntent #define MagickSetImageResolution GmMagickSetImageResolution #define MagickSetImageSavedType GmMagickSetImageSavedType #define MagickSetImageScene GmMagickSetImageScene #define MagickSetImageType GmMagickSetImageType #define MagickSetImageUnits GmMagickSetImageUnits #define MagickSetImageVirtualPixelMethod GmMagickSetImageVirtualPixelMethod #define MagickSetImageWhitePoint GmMagickSetImageWhitePoint #define MagickSetInterlaceScheme GmMagickSetInterlaceScheme #define MagickSetPassphrase GmMagickSetPassphrase #define MagickSetResolution GmMagickSetResolution #define MagickSetResolutionUnits GmMagickSetResolutionUnits #define MagickSetResourceLimit GmMagickSetResourceLimit #define MagickSetSamplingFactors GmMagickSetSamplingFactors #define MagickSetSize GmMagickSetSize #define MagickSharpenImage GmMagickSharpenImage #define MagickShaveImage GmMagickShaveImage #define MagickShearImage GmMagickShearImage #define MagickSolarizeImage GmMagickSolarizeImage #define MagickSpreadImage GmMagickSpreadImage #define MagickSteganoImage GmMagickSteganoImage #define MagickStereoImage GmMagickStereoImage #define MagickStripImage GmMagickStripImage #define MagickSwirlImage GmMagickSwirlImage #define MagickTextureImage GmMagickTextureImage #define MagickThresholdImage GmMagickThresholdImage #define MagickThresholdImageChannel GmMagickThresholdImageChannel #define MagickTintImage GmMagickTintImage #define MagickTransformImage GmMagickTransformImage #define MagickTransparentImage GmMagickTransparentImage #define MagickTrimImage GmMagickTrimImage #define MagickUnsharpMaskImage GmMagickUnsharpMaskImage #define MagickWaveImage GmMagickWaveImage #define MagickWhiteThresholdImage GmMagickWhiteThresholdImage #define MagickWriteImage GmMagickWriteImage #define MagickWriteImageBlob GmMagickWriteImageBlob #define MagickWriteImageFile GmMagickWriteImageFile #define MagickWriteImages GmMagickWriteImages #define MagickWriteImagesFile GmMagickWriteImagesFile #define NewMagickWand GmNewMagickWand #define NewPixelWand GmNewPixelWand #define NewPixelWands GmNewPixelWands #define PixelGetBlack GmPixelGetBlack #define PixelGetBlackQuantum GmPixelGetBlackQuantum #define PixelGetBlue GmPixelGetBlue #define PixelGetBlueQuantum GmPixelGetBlueQuantum #define PixelGetColorAsString GmPixelGetColorAsString #define PixelGetColorCount GmPixelGetColorCount #define PixelGetCyan GmPixelGetCyan #define PixelGetCyanQuantum GmPixelGetCyanQuantum #define PixelGetException GmPixelGetException #define PixelGetGreen GmPixelGetGreen #define PixelGetGreenQuantum GmPixelGetGreenQuantum #define PixelGetMagenta GmPixelGetMagenta #define PixelGetMagentaQuantum GmPixelGetMagentaQuantum #define PixelGetOpacity GmPixelGetOpacity #define PixelGetOpacityQuantum GmPixelGetOpacityQuantum #define PixelGetQuantumColor GmPixelGetQuantumColor #define PixelGetRed GmPixelGetRed #define PixelGetRedQuantum GmPixelGetRedQuantum #define PixelGetYellow GmPixelGetYellow #define PixelGetYellowQuantum GmPixelGetYellowQuantum #define PixelSetBlack GmPixelSetBlack #define PixelSetBlackQuantum GmPixelSetBlackQuantum #define PixelSetBlue GmPixelSetBlue #define PixelSetBlueQuantum GmPixelSetBlueQuantum #define PixelSetColor GmPixelSetColor #define PixelSetColorCount GmPixelSetColorCount #define PixelSetCyan GmPixelSetCyan #define PixelSetCyanQuantum GmPixelSetCyanQuantum #define PixelSetGreen GmPixelSetGreen #define PixelSetGreenQuantum GmPixelSetGreenQuantum #define PixelSetMagenta GmPixelSetMagenta #define PixelSetMagentaQuantum GmPixelSetMagentaQuantum #define PixelSetOpacity GmPixelSetOpacity #define PixelSetOpacityQuantum GmPixelSetOpacityQuantum #define PixelSetQuantumColor GmPixelSetQuantumColor #define PixelSetRed GmPixelSetRed #define PixelSetRedQuantum GmPixelSetRedQuantum #define PixelSetYellow GmPixelSetYellow #define PixelSetYellowQuantum GmPixelSetYellowQuantum #define QueryMagickColor GmQueryMagickColor #endif /* defined(PREFIX_MAGICK_SYMBOLS) */ #endif /* defined(_MAGICK_WAND_SYMBOLS_H) */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Blob.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002 // // Reference counted container class for Binary Large Objects (BLOBs) // #if !defined(Magick_BlobRef_header) #define Magick_BlobRef_header #include "Magick++/Include.h" #include namespace Magick { // Forward decl class BlobRef; class MagickDLLDecl Blob { public: enum Allocator { MallocAllocator, NewAllocator }; // Default constructor Blob ( void ); // Construct object with data, making a copy of the supplied data. Blob ( const void* data_, size_t length_ ); // Copy constructor (reference counted) Blob ( const Blob& blob_ ); // Destructor (reference counted) virtual ~Blob (); // Assignment operator (reference counted) Blob& operator= ( const Blob& blob_ ); // Update object contents from Base64-encoded string representation. void base64 ( const std::string base64_ ); // Return Base64-encoded string representation. std::string base64 ( void ); // Update object contents, making a copy of the supplied data. // Any existing data in the object is deallocated. void update ( const void* data_, size_t length_ ); // Update object contents, using supplied pointer directly (no // copy). Any existing data in the object is deallocated. The user // must ensure that the pointer supplied is not deleted or // otherwise modified after it has been supplied to this method. // Specify allocator_ as "MallocAllocator" if memory is allocated // via the C language malloc() function, or "NewAllocator" if // memory is allocated via C++ 'new'. void updateNoCopy ( void* data_, size_t length_, Allocator allocator_ = NewAllocator ); // Obtain pointer to data. The user should never try to modify or // free this data since the Blob class manages its own data. The // user must be finished with the data before allowing the Blob to // be destroyed since the pointer is invalid once the Blob is // destroyed. const void* data ( void ) const; // Obtain data length size_t length ( void ) const; protected: private: BlobRef * _blobRef; }; } // namespace Magick #endif // Magick_BlobRef_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/CoderInfo.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 2001-2010 // // CoderInfo Definition // // Container for image format support information. // #if !defined (Magick_CoderInfo_header) #define Magick_CoderInfo_header #include "Magick++/Include.h" #include namespace Magick { class MagickDLLDecl CoderInfo { public: enum MatchType { AnyMatch, // match any coder TrueMatch, // match coder if true FalseMatch // match coder if false }; // Default constructor CoderInfo ( void ); // Copy constructor CoderInfo ( const CoderInfo &coder_ ); // Construct with coder name CoderInfo ( const std::string &name_ ); // Destructor ~CoderInfo ( void ); // Format name std::string name( void ) const; // Format description std::string description( void ) const; // Format is readable bool isReadable( void ) const; // Format is writeable bool isWritable( void ) const; // Format supports multiple frames bool isMultiFrame( void ) const; // Assignment operator CoderInfo& operator= (const CoderInfo &coder_ ); // // Implemementation methods // CoderInfo ( const MagickLib::MagickInfo *magickInfo_ ); private: std::string _name; std::string _description; bool _isReadable; bool _isWritable; bool _isMultiFrame; }; } // namespace Magick // // Inlines // #endif // Magick_CoderInfo_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Color.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003, 2008 // // Color Implementation // #if !defined (Magick_Color_header) #define Magick_Color_header #include "Magick++/Include.h" #include namespace Magick { class MagickDLLDecl Color; // Compare two Color objects regardless of LHS/RHS int MagickDLLDecl operator == ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator != ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator > ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator < ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator >= ( const Magick::Color& left_, const Magick::Color& right_ ); int MagickDLLDecl operator <= ( const Magick::Color& left_, const Magick::Color& right_ ); // Base color class stores RGB components scaled to fit Quantum class MagickDLLDecl Color { public: Color ( Quantum red_, Quantum green_, Quantum blue_ ); Color ( Quantum red_, Quantum green_, Quantum blue_, Quantum alpha_ ); Color ( const std::string &x11color_ ); Color ( const char * x11color_ ); Color ( void ); virtual ~Color ( void ); Color ( const Color & color_ ); // Red color (range 0 to MaxRGB) void redQuantum ( Quantum red_ ); Quantum redQuantum ( void ) const; // Green color (range 0 to MaxRGB) void greenQuantum ( Quantum green_ ); Quantum greenQuantum ( void ) const; // Blue color (range 0 to MaxRGB) void blueQuantum ( Quantum blue_ ); Quantum blueQuantum ( void ) const; // Alpha level (range OpaqueOpacity=0 to TransparentOpacity=MaxRGB) void alphaQuantum ( Quantum alpha_ ); Quantum alphaQuantum ( void ) const; // Scaled (to 1.0) version of alpha for use in sub-classes // (range opaque=0 to transparent=1.0) void alpha ( double alpha_ ); double alpha ( void ) const; // Does object contain valid color? void isValid ( bool valid_ ); bool isValid ( void ) const; // Set color via X11 color specification string const Color& operator= ( const std::string &x11color_ ); const Color& operator= ( const char * x11color_ ); // Assignment operator Color& operator= ( const Color& color_ ); // Return X11 color specification string /* virtual */ operator std::string() const; // Return ImageMagick PixelPacket operator PixelPacket() const; // Construct color via ImageMagick PixelPacket Color ( const PixelPacket &color_ ); // Set color via ImageMagick PixelPacket const Color& operator= ( const PixelPacket &color_ ); // // Public methods beyond this point are for Magick++ use only. // // Obtain pixel intensity as a double double intensity ( void ) const { return (0.299*(_pixel->red)+0.587*(_pixel->green)+0.114*(_pixel->blue)); } // Scale a value expressed as a double (0-1) to Quantum range (0-MaxRGB) static Quantum scaleDoubleToQuantum( const double double_ ) { return (static_cast(double_*MaxRGB)); } // Scale a value expressed as a Quantum (0-MaxRGB) to double range (0-1) static double scaleQuantumToDouble( const Quantum quantum_ ) { return (static_cast(quantum_)/MaxRGB); } static double scaleQuantumToDouble( const double quantum_ ) { return (quantum_/MaxRGB); } protected: // PixelType specifies the interpretation of PixelPacket members // RGBPixel: // Red = red; // Green = green; // Blue = blue; // RGBAPixel: // Red = red; // Green = green; // Blue = blue; // Alpha = opacity; // CYMKPixel: // Cyan = red // Yellow = green // Magenta = blue // Black(K) = opacity enum PixelType { RGBPixel, RGBAPixel, CYMKPixel }; // Constructor to construct with PixelPacket* // Used to point Color at a pixel in an image Color ( PixelPacket* rep_, PixelType pixelType_ ); // Set pixel // Used to point Color at a pixel in an image void pixel ( PixelPacket* rep_, PixelType pixelType_ ); // PixelPacket represents a color pixel: // red = red (range 0 to MaxRGB) // green = green (range 0 to MaxRGB) // blue = blue (range 0 to MaxRGB) // opacity = alpha (range OpaqueOpacity=0 to TransparentOpacity=MaxRGB) // index = PseudoColor colormap index PixelPacket* _pixel; private: // Common initializer for PixelPacket representation void initPixel(); // Set true if we allocated pixel bool _pixelOwn; // Set true if pixel is "valid" bool _isValid; // Color type supported by _pixel PixelType _pixelType; }; // // HSL Colorspace colors // class MagickDLLDecl ColorHSL : public Color { public: ColorHSL ( double hue_, double saturation_, double luminosity_ ); ColorHSL ( void ); ColorHSL ( const Color & color_ ); /* virtual */ ~ColorHSL ( ); void hue ( double hue_ ); double hue ( void ) const; void saturation ( double saturation_ ); double saturation ( void ) const; void luminosity ( double luminosity_ ); double luminosity ( void ) const; // Assignment operator from base class ColorHSL& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorHSL ( PixelPacket* rep_, PixelType pixelType_ ); }; // // Grayscale RGB color // // Grayscale is simply RGB with equal parts of red, green, and blue // All double arguments have a valid range of 0.0 - 1.0. class MagickDLLDecl ColorGray : public Color { public: ColorGray ( double shade_ ); ColorGray ( void ); ColorGray ( const Color & color_ ); /* virtual */ ~ColorGray (); void shade ( double shade_ ); double shade ( void ) const; // Assignment operator from base class ColorGray& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorGray ( PixelPacket* rep_, PixelType pixelType_ ); }; // // Monochrome color // // Color arguments are constrained to 'false' (black pixel) and 'true' // (white pixel) class MagickDLLDecl ColorMono : public Color { public: ColorMono ( bool mono_ ); ColorMono ( void ); ColorMono ( const Color & color_ ); /* virtual */ ~ColorMono (); void mono ( bool mono_ ); bool mono ( void ) const; // Assignment operator from base class ColorMono& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorMono ( PixelPacket* rep_, PixelType pixelType_ ); }; // // RGB color // // All color arguments have a valid range of 0.0 - 1.0. class MagickDLLDecl ColorRGB : public Color { public: ColorRGB ( double red_, double green_, double blue_ ); ColorRGB ( void ); ColorRGB ( const Color & color_ ); /* virtual */ ~ColorRGB ( void ); void red ( double red_ ); double red ( void ) const; void green ( double green_ ); double green ( void ) const; void blue ( double blue_ ); double blue ( void ) const; // Assignment operator from base class ColorRGB& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorRGB ( PixelPacket* rep_, PixelType pixelType_ ); }; // // YUV Colorspace color // // Argument ranges: // Y: 0.0 through 1.0 // U: -0.5 through 0.5 // V: -0.5 through 0.5 class MagickDLLDecl ColorYUV : public Color { public: ColorYUV ( double y_, double u_, double v_ ); ColorYUV ( void ); ColorYUV ( const Color & color_ ); /* virtual */ ~ColorYUV ( void ); void u ( double u_ ); double u ( void ) const; void v ( double v_ ); double v ( void ) const; void y ( double y_ ); double y ( void ) const; // Assignment operator from base class ColorYUV& operator= ( const Color& color_ ); protected: // Constructor to construct with PixelPacket* ColorYUV ( PixelPacket* rep_, PixelType pixelType_ ); }; } // namespace Magick // // Inlines // // // Color // // Common initializer for PixelPacket representation // Initialized transparent black inline void Magick::Color::initPixel() { _pixel->red = 0; _pixel->green = 0; _pixel->blue = 0; _pixel->opacity = TransparentOpacity; } inline void Magick::Color::redQuantum ( Magick::Quantum red_ ) { _pixel->red = red_; _isValid = true; } inline Magick::Quantum Magick::Color::redQuantum ( void ) const { return _pixel->red; } inline void Magick::Color::greenQuantum ( Magick::Quantum green_ ) { _pixel->green = green_; _isValid = true; } inline Magick::Quantum Magick::Color::greenQuantum ( void ) const { return _pixel->green; } inline void Magick::Color::blueQuantum ( Magick::Quantum blue_ ) { _pixel->blue = blue_; _isValid = true; } inline Magick::Quantum Magick::Color::blueQuantum ( void ) const { return _pixel->blue; } inline void Magick::Color::alphaQuantum ( Magick::Quantum alpha_ ) { _pixel->opacity = alpha_; _isValid = true ; } inline Magick::Quantum Magick::Color::alphaQuantum ( void ) const { return _pixel->opacity; } // Return ImageMagick PixelPacket struct based on color. inline Magick::Color::operator MagickLib::PixelPacket () const { return *_pixel; } // Scaled version of alpha for use in sub-classes inline void Magick::Color::alpha ( double alpha_ ) { alphaQuantum( scaleDoubleToQuantum(alpha_) ); } inline double Magick::Color::alpha ( void ) const { return scaleQuantumToDouble( alphaQuantum() ); } // // ColorHSL // inline Magick::ColorHSL::ColorHSL ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } // // ColorGray // inline Magick::ColorGray::ColorGray ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } // // ColorMono // inline Magick::ColorMono::ColorMono ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } // // ColorRGB // inline Magick::ColorRGB::ColorRGB ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } inline void Magick::ColorRGB::red ( double red_ ) { redQuantum( scaleDoubleToQuantum(red_) ); } inline double Magick::ColorRGB::red ( void ) const { return scaleQuantumToDouble( redQuantum() ); } inline void Magick::ColorRGB::green ( double green_ ) { greenQuantum( scaleDoubleToQuantum(green_) ); } inline double Magick::ColorRGB::green ( void ) const { return scaleQuantumToDouble( greenQuantum() ); } inline void Magick::ColorRGB::blue ( double blue_ ) { blueQuantum( scaleDoubleToQuantum(blue_) ); } inline double Magick::ColorRGB::blue ( void ) const { return scaleQuantumToDouble( blueQuantum() ); } // // ColorYUV // inline Magick::ColorYUV::ColorYUV ( Magick::PixelPacket* rep_, Magick::Color::PixelType pixelType_ ) : Color( rep_, pixelType_ ) { } #endif // Magick_Color_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Drawable.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2018 // // Definition of Drawable (Graphic objects) // // The technique used for instantiating classes which derive from STL // templates is described in Microsoft MSDN Article ID: Q168958 // "HOWTO: Exporting STL Components Inside & Outside of a Class". // "http://support.microsoft.com/kb/168958" // // Note that version 3.0 of this article says that that only STL // container template which supports DLL export is and we are // not using as part of the Drawable implementation. // #if !defined(Magick_Drawable_header) #define Magick_Drawable_header #include "Magick++/Include.h" #include #include #include #include #include "Magick++/Color.h" #include "Magick++/Geometry.h" #if defined(MagickDLLExplicitTemplate) # if defined(MAGICK_PLUSPLUS_IMPLEMENTATION) # define MagickDrawableExtern # else # pragma warning( disable: 4231 ) // Disable warning regarding using extern # define MagickDrawableExtern extern # endif // MAGICK_PLUSPLUS_IMPLEMENTATION #else # define MagickDrawableExtern #endif // MagickDLLExplicitTemplate namespace Magick { #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-warning-option" #pragma clang diagnostic ignored "-Wunused-private-field" #endif /* if defined(__clang__) */ // // Representation of an x,y coordinate // class MagickDLLDecl Coordinate { public: // Default Constructor Coordinate ( void ) : _x(0), _y(0) { } // Constructor, setting first & second Coordinate ( double x_, double y_ ) : _x(x_), _y(y_) { } // Destructor virtual ~Coordinate () { } // x coordinate member void x ( double x_ ) { _x = x_; } double x ( void ) const { return _x; } // y coordinate member void y ( double y_ ) { _y = y_; } double y ( void ) const { return _y; } private: double _x; double _y; }; typedef std::list CoordinateList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate // Compare two Coordinate objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator != ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator > ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator < ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator >= ( const Coordinate& left_, const Coordinate& right_ ); MagickDLLDeclExtern int operator <= ( const Coordinate& left_, const Coordinate& right_ ); // // Base class for all drawable objects // //struct MagickDLLDecl std::unary_function; class MagickDLLDecl DrawableBase: public std::unary_function { public: // Constructor DrawableBase ( void ) { } // Destructor virtual ~DrawableBase ( void ); // Operator to invoke equivalent draw API call virtual void operator()( MagickLib::DrawContext ) const = 0; // Return polymorphic copy of object virtual DrawableBase* copy() const = 0; private: }; // // Representation of a drawable surrogate object to manage drawable objects // #undef Drawable // Conflict with class MagickDLLDecl Drawable { public: // Constructor Drawable ( void ); // Construct from DrawableBase Drawable ( const DrawableBase& original_ ); // Destructor ~Drawable ( void ); // Copy constructor Drawable ( const Drawable& original_ ); // Assignment operator Drawable& operator= (const Drawable& original_ ); // Operator to invoke contained object void operator()( MagickLib::DrawContext context_ ) const; private: DrawableBase* dp; }; // Compare two Drawable objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator != ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator > ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator < ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator >= ( const Drawable& left_, const Drawable& right_ ); MagickDLLDeclExtern int operator <= ( const Drawable& left_, const Drawable& right_ ); typedef std::list DrawableList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate // // Base class for all drawable path elements for use with // DrawablePath // class MagickDLLDecl VPathBase { public: // Constructor VPathBase ( void ) { } // Destructor virtual ~VPathBase ( void ); // Assignment operator // const VPathBase& operator= (const VPathBase& original_ ); // Operator to invoke equivalent draw API call virtual void operator()( MagickLib::DrawContext context_ ) const = 0; // Return polymorphic copy of object virtual VPathBase* copy() const = 0; }; // // Representation of a drawable path element surrogate object to // manage drawable path elements so they may be passed as a list to // DrawablePath. // class MagickDLLDecl VPath { public: // Constructor VPath ( void ); // Construct from VPathBase VPath ( const VPathBase& original_ ); // Destructor virtual ~VPath ( void ); // Copy constructor VPath ( const VPath& original_ ); // Assignment operator VPath& operator= (const VPath& original_ ); // Operator to invoke contained object void operator()( MagickLib::DrawContext context_ ) const; private: VPathBase* dp; }; // Compare two VPath objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator != ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator > ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator < ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator >= ( const VPath& left_, const VPath& right_ ); MagickDLLDeclExtern int operator <= ( const VPath& left_, const VPath& right_ ); typedef std::list VPathList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate // // Drawable Objects // // Affine (scaling, rotation, and translation) class MagickDLLDecl DrawableAffine : public DrawableBase { public: DrawableAffine ( double sx_, double sy_, double rx_, double ry_, double tx_, double ty_ ); DrawableAffine ( void ); /*virtual*/ ~DrawableAffine( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void sx( const double sx_ ) { _affine.sx = sx_; } double sx( void ) const { return _affine.sx; } void sy( const double sy_ ) { _affine.sy = sy_; } double sy( void ) const { return _affine.sy; } void rx( const double rx_ ) { _affine.rx = rx_; } double rx( void ) const { return _affine.rx; } void ry( const double ry_ ) { _affine.ry = ry_; } double ry( void ) const { return _affine.ry; } void tx( const double tx_ ) { _affine.tx = tx_; } double tx( void ) const { return _affine.tx; } void ty( const double ty_ ) { _affine.ty = ty_; } double ty( void ) const { return _affine.ty; } private: MagickLib::AffineMatrix _affine; }; // Arc class MagickDLLDecl DrawableArc : public DrawableBase { public: DrawableArc ( double startX_, double startY_, double endX_, double endY_, double startDegrees_, double endDegrees_ ) : _startX(startX_), _startY(startY_), _endX(endX_), _endY(endY_), _startDegrees(startDegrees_), _endDegrees(endDegrees_) { } /*virtual*/ ~DrawableArc( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void startX( double startX_ ) { _startX = startX_; } double startX( void ) const { return _startX; } void startY( double startY_ ) { _startY = startY_; } double startY( void ) const { return _startY; } void endX( double endX_ ) { _endX = endX_; } double endX( void ) const { return _endX; } void endY( double endY_ ) { _endY = endY_; } double endY( void ) const { return _endY; } void startDegrees( double startDegrees_ ) { _startDegrees = startDegrees_; } double startDegrees( void ) const { return _startDegrees; } void endDegrees( double endDegrees_ ) { _endDegrees = endDegrees_; } double endDegrees( void ) const { return _endDegrees; } private: double _startX; double _startY; double _endX; double _endY; double _startDegrees; double _endDegrees; }; // Bezier curve (Coordinate list must contain at least three members) class MagickDLLDecl DrawableBezier : public DrawableBase { public: // Construct from coordinates DrawableBezier ( const CoordinateList &coordinates_ ); // Copy constructor DrawableBezier ( const DrawableBezier& original_ ); // Destructor /*virtual*/ ~DrawableBezier ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: CoordinateList _coordinates; }; // Pop (terminate) clip path definition class MagickDLLDecl DrawablePopClipPath : public DrawableBase { public: DrawablePopClipPath ( void ) : _dummy(0) { } /*virtual*/ ~DrawablePopClipPath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: int _dummy; }; // Push (create) Clip path definition class MagickDLLDecl DrawablePushClipPath : public DrawableBase { public: DrawablePushClipPath ( const std::string &id_); DrawablePushClipPath ( const DrawablePushClipPath& original_ ); /*virtual*/ ~DrawablePushClipPath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: std::string _id; }; // Named Clip Path class MagickDLLDecl DrawableClipPath : public DrawableBase { public: DrawableClipPath ( const std::string &id_ ); DrawableClipPath ( const DrawableClipPath& original_ ); /*virtual*/ ~DrawableClipPath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void clip_path( const std::string &id_ ) { _id = id_.c_str(); //multithread safe } std::string clip_path( void ) const { return _id; } private: std::string _id; }; // Circle class MagickDLLDecl DrawableCircle : public DrawableBase { public: DrawableCircle ( double originX_, double originY_, double perimX_, double perimY_ ) : _originX(originX_), _originY(originY_), _perimX(perimX_), _perimY(perimY_) { } /*virtual*/ ~DrawableCircle ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void originX( double originX_ ) { _originX = originX_; } double originX( void ) const { return _originX; } void originY( double originY_ ) { _originY = originY_; } double originY( void ) const { return _originY; } void perimX( double perimX_ ) { _perimX = perimX_; } double perimX( void ) const { return _perimX; } void perimY( double perimY_ ) { _perimY = perimY_; } double perimY( void ) const { return _perimY; } private: double _originX; double _originY; double _perimX; double _perimY; }; // Colorize at point using PaintMethod class MagickDLLDecl DrawableColor : public DrawableBase { public: DrawableColor ( double x_, double y_, PaintMethod paintMethod_ ) : _x(x_), _y(y_), _paintMethod(paintMethod_) { } /*virtual*/ ~DrawableColor ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } void paintMethod( PaintMethod paintMethod_ ) { _paintMethod = paintMethod_; } PaintMethod paintMethod( void ) const { return _paintMethod; } private: double _x; double _y; PaintMethod _paintMethod; }; // Draw image at point, scaled to size specified by width and height class MagickDLLDecl Image; class MagickDLLDecl DrawableCompositeImage : public DrawableBase { public: DrawableCompositeImage ( double x_, double y_, const std::string &filename_ ); DrawableCompositeImage ( double x_, double y_, const Image &image_ ); DrawableCompositeImage ( double x_, double y_, double width_, double height_, const std::string &filename_ ); DrawableCompositeImage ( double x_, double y_, double width_, double height_, const Image &image_ ); DrawableCompositeImage ( double x_, double y_, double width_, double height_, const std::string &filename_, CompositeOperator composition_ ); DrawableCompositeImage ( double x_, double y_, double width_, double height_, const Image &image_, CompositeOperator composition_ ); // Copy constructor DrawableCompositeImage ( const DrawableCompositeImage& original_ ); // Destructor /*virtual*/ ~DrawableCompositeImage( void ); // Assignment operator DrawableCompositeImage& operator= (const DrawableCompositeImage& original_ ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void composition( CompositeOperator composition_ ) { _composition = composition_; } CompositeOperator composition( void ) const { return _composition; } void filename( const std::string &image_ ); std::string filename( void ) const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } void width( double width_ ) { _width = width_; } double width( void ) const { return _width; } void height( double height_ ) { _height = height_; } double height( void ) const { return _height; } void image( const Image &image_ ); Magick::Image image( void ) const; // Specify image format used to output Base64 inlined image data. void magick( std::string magick_ ); std::string magick( void ); private: CompositeOperator _composition; double _x; double _y; double _width; double _height; Image* _image; }; // Ellipse class MagickDLLDecl DrawableEllipse : public DrawableBase { public: DrawableEllipse ( double originX_, double originY_, double radiusX_, double radiusY_, double arcStart_, double arcEnd_ ) : _originX(originX_), _originY(originY_), _radiusX(radiusX_), _radiusY(radiusY_), _arcStart(arcStart_), _arcEnd(arcEnd_) { } /*virtual*/ ~DrawableEllipse( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void originX( double originX_ ) { _originX = originX_; } double originX( void ) const { return _originX; } void originY( double originY_ ) { _originY = originY_; } double originY( void ) const { return _originY; } void radiusX( double radiusX_ ) { _radiusX = radiusX_; } double radiusX( void ) const { return _radiusX; } void radiusY( double radiusY_ ) { _radiusY = radiusY_; } double radiusY( void ) const { return _radiusY; } void arcStart( double arcStart_ ) { _arcStart = arcStart_; } double arcStart( void ) const { return _arcStart; } void arcEnd( double arcEnd_ ) { _arcEnd = arcEnd_; } double arcEnd( void ) const { return _arcEnd; } private: double _originX; double _originY; double _radiusX; double _radiusY; double _arcStart; double _arcEnd; }; // Specify drawing fill color class MagickDLLDecl DrawableFillColor : public DrawableBase { public: DrawableFillColor ( const Color &color_ ); DrawableFillColor ( const DrawableFillColor& original_ ); /*virtual*/ ~DrawableFillColor( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void color( const Color &color_ ) { _color = color_; } Color color( void ) const { return _color; } private: Color _color; }; // Specify fill rule (fill-rule) class MagickDLLDecl DrawableFillRule : public DrawableBase { public: DrawableFillRule ( const FillRule fillRule_ ) : _fillRule(fillRule_) { } /*virtual*/ ~DrawableFillRule ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void fillRule( const FillRule fillRule_ ) { _fillRule = fillRule_; } FillRule fillRule( void ) const { return _fillRule; } private: FillRule _fillRule; }; // Specify drawing fill opacity class MagickDLLDecl DrawableFillOpacity : public DrawableBase { public: DrawableFillOpacity ( double opacity_ ) : _opacity(opacity_) { } /*virtual*/ ~DrawableFillOpacity ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void opacity( double opacity_ ) { _opacity = opacity_; } double opacity( void ) const { return _opacity; } private: double _opacity; }; // Specify text font class MagickDLLDecl DrawableFont : public DrawableBase { public: DrawableFont ( const std::string &font_ ); DrawableFont ( const std::string &family_, StyleType style_, const unsigned long weight_, StretchType stretch_ ); DrawableFont ( const DrawableFont& original_ ); /*virtual*/ ~DrawableFont ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void font( const std::string &font_ ) { _font = font_; } std::string font( void ) const { return _font; } private: std::string _font; std::string _family; StyleType _style; unsigned long _weight; StretchType _stretch; }; // Specify text positioning gravity class MagickDLLDecl DrawableGravity : public DrawableBase { public: DrawableGravity ( GravityType gravity_ ) : _gravity(gravity_) { } /*virtual*/ ~DrawableGravity ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void gravity( GravityType gravity_ ) { _gravity = gravity_; } GravityType gravity( void ) const { return _gravity; } private: GravityType _gravity; }; // Line class MagickDLLDecl DrawableLine : public DrawableBase { public: DrawableLine ( double startX_, double startY_, double endX_, double endY_ ) : _startX(startX_), _startY(startY_), _endX(endX_), _endY(endY_) { } /*virtual*/ ~DrawableLine ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void startX( double startX_ ) { _startX = startX_; } double startX( void ) const { return _startX; } void startY( double startY_ ) { _startY = startY_; } double startY( void ) const { return _startY; } void endX( double endX_ ) { _endX = endX_; } double endX( void ) const { return _endX; } void endY( double endY_ ) { _endY = endY_; } double endY( void ) const { return _endY; } private: double _startX; double _startY; double _endX; double _endY; }; // Change pixel matte value to transparent using PaintMethod class MagickDLLDecl DrawableMatte : public DrawableBase { public: DrawableMatte ( double x_, double y_, PaintMethod paintMethod_ ) : _x(x_), _y(y_), _paintMethod(paintMethod_) { } /*virtual*/ ~DrawableMatte ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } void paintMethod( PaintMethod paintMethod_ ) { _paintMethod = paintMethod_; } PaintMethod paintMethod( void ) const { return _paintMethod; } private: double _x; double _y; PaintMethod _paintMethod; }; // Drawable Path class MagickDLLDecl DrawablePath : public DrawableBase { public: DrawablePath ( const VPathList &path_ ); DrawablePath ( const DrawablePath& original_ ); /*virtual*/ ~DrawablePath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: VPathList _path; }; // Point class MagickDLLDecl DrawablePoint : public DrawableBase { public: DrawablePoint ( double x_, double y_ ) : _x(x_), _y(y_) { } /*virtual*/ ~DrawablePoint ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x; double _y; }; // Text pointsize class MagickDLLDecl DrawablePointSize : public DrawableBase { public: DrawablePointSize ( double pointSize_ ) : _pointSize(pointSize_) { } /*virtual*/ ~DrawablePointSize ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void pointSize( double pointSize_ ) { _pointSize = pointSize_; } double pointSize( void ) const { return _pointSize; } private: double _pointSize; }; // Polygon (Coordinate list must contain at least three members) class MagickDLLDecl DrawablePolygon : public DrawableBase { public: DrawablePolygon ( const CoordinateList &coordinates_ ); DrawablePolygon ( const DrawablePolygon& original_ ); /*virtual*/ ~DrawablePolygon ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: CoordinateList _coordinates; }; // Polyline (Coordinate list must contain at least three members) class MagickDLLDecl DrawablePolyline : public DrawableBase { public: DrawablePolyline ( const CoordinateList &coordinates_ ); DrawablePolyline ( const DrawablePolyline& original_ ); /*virtual*/ ~DrawablePolyline ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: CoordinateList _coordinates; }; // Pop Graphic Context class MagickDLLDecl DrawablePopGraphicContext : public DrawableBase { public: DrawablePopGraphicContext ( void ) : _dummy(0) { } /*virtual*/ ~DrawablePopGraphicContext ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: int _dummy; }; // Push Graphic Context class MagickDLLDecl DrawablePushGraphicContext : public DrawableBase { public: DrawablePushGraphicContext ( void ) : _dummy(0) { } /*virtual*/ ~DrawablePushGraphicContext ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: int _dummy; }; // Pop (terminate) Pattern definition class MagickDLLDecl DrawablePopPattern : public DrawableBase { public: DrawablePopPattern ( void ) : _dummy(0) { } /*virtual*/ ~DrawablePopPattern ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: int _dummy; }; // Push (create) Pattern definition class MagickDLLDecl DrawablePushPattern : public DrawableBase { public: DrawablePushPattern ( const std::string &id_, long x_, long y_, long width_, long height_ ); DrawablePushPattern ( const DrawablePushPattern& original_ ); /*virtual*/ ~DrawablePushPattern ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; private: std::string _id; long _x; long _y; long _width; long _height; }; // Rectangle class MagickDLLDecl DrawableRectangle : public DrawableBase { public: DrawableRectangle ( double upperLeftX_, double upperLeftY_, double lowerRightX_, double lowerRightY_ ) : _upperLeftX(upperLeftX_), _upperLeftY(upperLeftY_), _lowerRightX(lowerRightX_), _lowerRightY(lowerRightY_) { } /*virtual*/ ~DrawableRectangle ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void upperLeftX( double upperLeftX_ ) { _upperLeftX = upperLeftX_; } double upperLeftX( void ) const { return _upperLeftX; } void upperLeftY( double upperLeftY_ ) { _upperLeftY = upperLeftY_; } double upperLeftY( void ) const { return _upperLeftY; } void lowerRightX( double lowerRightX_ ) { _lowerRightX = lowerRightX_; } double lowerRightX( void ) const { return _lowerRightX; } void lowerRightY( double lowerRightY_ ) { _lowerRightY = lowerRightY_; } double lowerRightY( void ) const { return _lowerRightY; } private: double _upperLeftX; double _upperLeftY; double _lowerRightX; double _lowerRightY; }; // Apply Rotation class MagickDLLDecl DrawableRotation : public DrawableBase { public: DrawableRotation ( double angle_ ) : _angle( angle_ ) { } /*virtual*/ ~DrawableRotation ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void angle( double angle_ ) { _angle = angle_; } double angle( void ) const { return _angle; } private: double _angle; }; // Round Rectangle class MagickDLLDecl DrawableRoundRectangle : public DrawableBase { public: DrawableRoundRectangle ( double centerX_, double centerY_, double width_, double hight_, double cornerWidth_, double cornerHeight_ ) : _centerX(centerX_), _centerY(centerY_), _width(width_), _hight(hight_), _cornerWidth(cornerWidth_), _cornerHeight(cornerHeight_) { } /*virtual*/ ~DrawableRoundRectangle ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void centerX( double centerX_ ) { _centerX = centerX_; } double centerX( void ) const { return _centerX; } void centerY( double centerY_ ) { _centerY = centerY_; } double centerY( void ) const { return _centerY; } void width( double width_ ) { _width = width_; } double width( void ) const { return _width; } void hight( double hight_ ) { _hight = hight_; } double hight( void ) const { return _hight; } void cornerWidth( double cornerWidth_ ) { _cornerWidth = cornerWidth_; } double cornerWidth( void ) const { return _cornerWidth; } void cornerHeight( double cornerHeight_ ) { _cornerHeight = cornerHeight_; } double cornerHeight( void ) const { return _cornerHeight; } private: double _centerX; double _centerY; double _width; double _hight; double _cornerWidth; double _cornerHeight; }; // Apply Scaling class MagickDLLDecl DrawableScaling : public DrawableBase { public: DrawableScaling ( double x_, double y_ ) : _x(x_), _y(y_) { } /*virtual*/ ~DrawableScaling ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x; double _y; }; // Apply Skew in X direction class MagickDLLDecl DrawableSkewX : public DrawableBase { public: DrawableSkewX ( double angle_ ) : _angle(angle_) { } /*virtual*/ ~DrawableSkewX ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void angle( double angle_ ) { _angle = angle_; } double angle( void ) const { return _angle; } private: double _angle; }; // Apply Skew in Y direction class MagickDLLDecl DrawableSkewY : public DrawableBase { public: DrawableSkewY ( double angle_ ) : _angle(angle_) { } /*virtual*/ ~DrawableSkewY ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void angle( double angle_ ) { _angle = angle_; } double angle( void ) const { return _angle; } private: double _angle; }; // Stroke dasharray // // dasharray_ is an allocated array terminated by value 0.0 or 0. // The array is copied so the original does not need to be preserved. // Pass a null pointer to clear an existing dash array setting. class MagickDLLDecl DrawableDashArray : public DrawableBase { public: DrawableDashArray( const double* dasharray_ ); DrawableDashArray( const unsigned int* dasharray_ ); // Deprecated DrawableDashArray( const Magick::DrawableDashArray &original_ ); /*virtual*/ ~DrawableDashArray( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void dasharray( const double* dasharray_ ); void dasharray( const unsigned int* dasharray_ ); // Deprecated const double* dasharray( void ) const { return _dasharray; } DrawableDashArray& operator=(const Magick::DrawableDashArray &original_); private: size_t _size; double *_dasharray; }; // Stroke dashoffset class MagickDLLDecl DrawableDashOffset : public DrawableBase { public: DrawableDashOffset ( const double offset_ ) : _offset(offset_) { } /*virtual*/ ~DrawableDashOffset ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void offset( const double offset_ ) { _offset = offset_; } double offset( void ) const { return _offset; } private: double _offset; }; // Stroke linecap class MagickDLLDecl DrawableStrokeLineCap : public DrawableBase { public: DrawableStrokeLineCap ( LineCap linecap_ ) : _linecap(linecap_) { } /*virtual*/ ~DrawableStrokeLineCap ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void linecap( LineCap linecap_ ) { _linecap = linecap_; } LineCap linecap( void ) const { return _linecap; } private: LineCap _linecap; }; // Stroke linejoin class MagickDLLDecl DrawableStrokeLineJoin : public DrawableBase { public: DrawableStrokeLineJoin ( LineJoin linejoin_ ) : _linejoin(linejoin_) { } /*virtual*/ ~DrawableStrokeLineJoin ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void linejoin( LineJoin linejoin_ ) { _linejoin = linejoin_; } LineJoin linejoin( void ) const { return _linejoin; } private: LineJoin _linejoin; }; // Stroke miterlimit class MagickDLLDecl DrawableMiterLimit : public DrawableBase { public: DrawableMiterLimit ( unsigned int miterlimit_ ) : _miterlimit(miterlimit_) { } /*virtual*/ ~DrawableMiterLimit ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void miterlimit( unsigned int miterlimit_ ) { _miterlimit = miterlimit_; } unsigned int miterlimit( void ) const { return _miterlimit; } private: unsigned int _miterlimit; }; // Stroke antialias class MagickDLLDecl DrawableStrokeAntialias : public DrawableBase { public: DrawableStrokeAntialias ( bool flag_ ) : _flag(flag_) { } /*virtual*/ ~DrawableStrokeAntialias ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void flag( bool flag_ ) { _flag = flag_; } bool flag( void ) const { return _flag; } private: bool _flag; }; // Stroke color class MagickDLLDecl DrawableStrokeColor : public DrawableBase { public: DrawableStrokeColor ( const Color &color_ ); DrawableStrokeColor ( const DrawableStrokeColor& original_ ); /*virtual*/ ~DrawableStrokeColor ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void color( const Color& color_ ) { _color = color_; } Color color( void ) const { return _color; } private: Color _color; }; // Stroke opacity class MagickDLLDecl DrawableStrokeOpacity : public DrawableBase { public: DrawableStrokeOpacity ( double opacity_ ) : _opacity(opacity_) { } /*virtual*/ ~DrawableStrokeOpacity ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void opacity( double opacity_ ) { _opacity = opacity_; } double opacity( void ) const { return _opacity; } private: double _opacity; }; // Stroke width class MagickDLLDecl DrawableStrokeWidth : public DrawableBase { public: DrawableStrokeWidth ( double width_ ) : _width(width_) { } /*virtual*/ ~DrawableStrokeWidth ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void width( double width_ ) { _width = width_; } double width( void ) const { return _width; } private: double _width; }; // Draw text at point class MagickDLLDecl DrawableText : public DrawableBase { public: DrawableText ( const double x_, const double y_, const std::string &text_ ); DrawableText ( const double x_, const double y_, const std::string &text_, const std::string &encoding_); DrawableText ( const DrawableText& original_ ); /*virtual*/ ~DrawableText ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void encoding(const std::string &encoding_) { _encoding = encoding_; } void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } void text( const std::string &text_ ) { _text = text_; } std::string text( void ) const { return _text; } private: double _x; double _y; std::string _text; std::string _encoding; }; // Text antialias class MagickDLLDecl DrawableTextAntialias : public DrawableBase { public: DrawableTextAntialias ( bool flag_ ); DrawableTextAntialias( const DrawableTextAntialias &original_ ); /*virtual*/ ~DrawableTextAntialias ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void flag( bool flag_ ) { _flag = flag_; } bool flag( void ) const { return _flag; } private: bool _flag; }; // Decoration (text decoration) class MagickDLLDecl DrawableTextDecoration : public DrawableBase { public: DrawableTextDecoration ( DecorationType decoration_ ); DrawableTextDecoration ( const DrawableTextDecoration& original_ ); /*virtual*/ ~DrawableTextDecoration( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void decoration( DecorationType decoration_ ) { _decoration = decoration_; } DecorationType decoration( void ) const { return _decoration; } private: DecorationType _decoration; }; // Text undercolor box class MagickDLLDecl DrawableTextUnderColor : public DrawableBase { public: DrawableTextUnderColor ( const Color &color_ ); DrawableTextUnderColor ( const DrawableTextUnderColor& original_ ); /*virtual*/ ~DrawableTextUnderColor ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void color( const Color& color_ ) { _color = color_; } Color color( void ) const { return _color; } private: Color _color; }; // Apply Translation class MagickDLLDecl DrawableTranslation : public DrawableBase { public: DrawableTranslation ( double x_, double y_ ) : _x(x_), _y(y_) { } /*virtual*/ ~DrawableTranslation ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x; double _y; }; // Set the size of the viewbox class MagickDLLDecl DrawableViewbox : public DrawableBase { public: DrawableViewbox(unsigned long x1_, unsigned long y1_, unsigned long x2_, unsigned long y2_) : _x1(x1_), _y1(y1_), _x2(x2_), _y2(y2_) { } /*virtual*/ ~DrawableViewbox ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ DrawableBase* copy() const; void x1( unsigned long x1_ ) { _x1 = x1_; } unsigned long x1( void ) const { return _x1; } void y1( unsigned long y1_ ) { _y1 = y1_; } unsigned long y1( void ) const { return _y1; } void x2( unsigned long x2_ ) { _x2 = x2_; } unsigned long x2( void ) const { return _x2; } void y2( unsigned long y2_ ) { _y2 = y2_; } unsigned long y2( void ) const { return _y2; } private: unsigned long _x1; unsigned long _y1; unsigned long _x2; unsigned long _y2; }; // // Path Element Classes To Support DrawablePath // class MagickDLLDecl PathArcArgs { public: // Default constructor PathArcArgs( void ); // Path arc argument PathArcArgs( double radiusX_, double radiusY_, double xAxisRotation_, bool largeArcFlag_, bool sweepFlag_, double x_, double y_ ); PathArcArgs( const PathArcArgs &original_ ); ~PathArcArgs ( void ); void radiusX( double radiusX_ ) { _radiusX = radiusX_; } double radiusX( void ) const { return _radiusX; } void radiusY( double radiusY_ ) { _radiusY = radiusY_; } double radiusY( void ) const { return _radiusY; } void xAxisRotation( double xAxisRotation_ ) { _xAxisRotation = xAxisRotation_; } double xAxisRotation( void ) const { return _xAxisRotation; } void largeArcFlag( bool largeArcFlag_ ) { _largeArcFlag = largeArcFlag_; } bool largeArcFlag( void ) const { return _largeArcFlag; } void sweepFlag( bool sweepFlag_ ) { _sweepFlag = sweepFlag_; } bool sweepFlag( void ) const { return _sweepFlag; } void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _radiusX; // X radius double _radiusY; // Y radius double _xAxisRotation; // Rotation relative to X axis bool _largeArcFlag; // Draw longer of the two matching arcs bool _sweepFlag; // Draw arc matching clock-wise rotation double _x; // End-point X double _y; // End-point Y }; // Compare two PathArcArgs objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator != ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator > ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator < ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator >= ( const PathArcArgs& left_, const PathArcArgs& right_ ); MagickDLLDeclExtern int operator <= ( const PathArcArgs& left_, const PathArcArgs& right_ ); typedef std::list PathArcArgsList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate // Path Arc (Elliptical Arc) class MagickDLLDecl PathArcAbs : public VPathBase { public: // Draw a single arc segment PathArcAbs ( const PathArcArgs &coordinates_ ); // Draw multiple arc segments PathArcAbs ( const PathArcArgsList &coordinates_ ); // Copy constructor PathArcAbs ( const PathArcAbs& original_ ); // Destructor /*virtual*/ ~PathArcAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathArcArgsList _coordinates; }; class MagickDLLDecl PathArcRel : public VPathBase { public: // Draw a single arc segment PathArcRel ( const PathArcArgs &coordinates_ ); // Draw multiple arc segments PathArcRel ( const PathArcArgsList &coordinates_ ); PathArcRel ( const PathArcRel& original_ ); /*virtual*/ ~PathArcRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathArcArgsList _coordinates; }; // Path Closepath class MagickDLLDecl PathClosePath : public VPathBase { public: PathClosePath ( void ) : _dummy(0) { } /*virtual*/ ~PathClosePath ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: int _dummy; }; // // Curveto (Cubic Bezier) // class MagickDLLDecl PathCurvetoArgs { public: PathCurvetoArgs( void ); PathCurvetoArgs( double x1_, double y1_, double x2_, double y2_, double x_, double y_ ); PathCurvetoArgs( const PathCurvetoArgs &original_ ); ~PathCurvetoArgs ( void ); void x1( double x1_ ) { _x1 = x1_; } double x1( void ) const { return _x1; } void y1( double y1_ ) { _y1 = y1_; } double y1( void ) const { return _y1; } void x2( double x2_ ) { _x2 = x2_; } double x2( void ) const { return _x2; } void y2( double y2_ ) { _y2 = y2_; } double y2( void ) const { return _y2; } void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x1; double _y1; double _x2; double _y2; double _x; double _y; }; // Compare two PathCurvetoArgs objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator != ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator > ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator < ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator >= ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); MagickDLLDeclExtern int operator <= ( const PathCurvetoArgs& left_, const PathCurvetoArgs& right_ ); typedef std::list PathCurveToArgsList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate class MagickDLLDecl PathCurvetoAbs : public VPathBase { public: // Draw a single curve PathCurvetoAbs ( const PathCurvetoArgs &args_ ); // Draw multiple curves PathCurvetoAbs ( const PathCurveToArgsList &args_ ); // Copy constructor PathCurvetoAbs ( const PathCurvetoAbs& original_ ); // Destructor /*virtual*/ ~PathCurvetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathCurveToArgsList _args; }; class MagickDLLDecl PathCurvetoRel : public VPathBase { public: // Draw a single curve PathCurvetoRel ( const PathCurvetoArgs &args_ ); // Draw multiple curves PathCurvetoRel ( const PathCurveToArgsList &args_ ); // Copy constructor PathCurvetoRel ( const PathCurvetoRel& original_ ); /*virtual*/ ~PathCurvetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathCurveToArgsList _args; }; class MagickDLLDecl PathSmoothCurvetoAbs : public VPathBase { public: // Draw a single curve PathSmoothCurvetoAbs ( const Magick::Coordinate &coordinates_ ); // Draw multiple curves PathSmoothCurvetoAbs ( const CoordinateList &coordinates_ ); // Copy constructor PathSmoothCurvetoAbs ( const PathSmoothCurvetoAbs& original_ ); /*virtual*/ ~PathSmoothCurvetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; class MagickDLLDecl PathSmoothCurvetoRel : public VPathBase { public: // Draw a single curve PathSmoothCurvetoRel ( const Coordinate &coordinates_ ); // Draw multiple curves PathSmoothCurvetoRel ( const CoordinateList &coordinates_ ); // Copy constructor PathSmoothCurvetoRel ( const PathSmoothCurvetoRel& original_ ); // Destructor /*virtual*/ ~PathSmoothCurvetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; // // Quadratic Curveto (Quadratic Bezier) // class MagickDLLDecl PathQuadraticCurvetoArgs { public: // Default constructor PathQuadraticCurvetoArgs( void ); // Parameterized constructor PathQuadraticCurvetoArgs( double x1_, double y1_, double x_, double y_ ); // Copy constructor PathQuadraticCurvetoArgs( const PathQuadraticCurvetoArgs &original_ ); ~PathQuadraticCurvetoArgs ( void ); void x1( double x1_ ) { _x1 = x1_; } double x1( void ) const { return _x1; } void y1( double y1_ ) { _y1 = y1_; } double y1( void ) const { return _y1; } void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _x1; double _y1; double _x; double _y; }; // Compare two PathQuadraticCurvetoArgs objects regardless of LHS/RHS MagickDLLDeclExtern int operator == ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_ ); MagickDLLDeclExtern int operator != ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_); MagickDLLDeclExtern int operator > ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_); MagickDLLDeclExtern int operator < ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_); MagickDLLDeclExtern int operator >= ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_ ); MagickDLLDeclExtern int operator <= ( const PathQuadraticCurvetoArgs& left_, const PathQuadraticCurvetoArgs& right_ ); typedef std::list PathQuadraticCurvetoArgsList; #if defined(MagickDLLExplicitTemplate) MagickDrawableExtern template class MagickDLLDecl std::allocator; // MagickDrawableExtern template class MagickDLLDecl // std::list >; #endif // MagickDLLExplicitTemplate class MagickDLLDecl PathQuadraticCurvetoAbs : public VPathBase { public: // Draw a single curve PathQuadraticCurvetoAbs ( const Magick::PathQuadraticCurvetoArgs &args_ ); // Draw multiple curves PathQuadraticCurvetoAbs ( const PathQuadraticCurvetoArgsList &args_ ); // Copy constructor PathQuadraticCurvetoAbs ( const PathQuadraticCurvetoAbs& original_ ); // Destructor /*virtual*/ ~PathQuadraticCurvetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathQuadraticCurvetoArgsList _args; }; class MagickDLLDecl PathQuadraticCurvetoRel : public VPathBase { public: // Draw a single curve PathQuadraticCurvetoRel ( const Magick::PathQuadraticCurvetoArgs &args_ ); // Draw multiple curves PathQuadraticCurvetoRel ( const PathQuadraticCurvetoArgsList &args_ ); // Copy constructor PathQuadraticCurvetoRel ( const PathQuadraticCurvetoRel& original_ ); // Destructor /*virtual*/ ~PathQuadraticCurvetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: PathQuadraticCurvetoArgsList _args; }; class MagickDLLDecl PathSmoothQuadraticCurvetoAbs : public VPathBase { public: // Draw a single curve PathSmoothQuadraticCurvetoAbs ( const Magick::Coordinate &coordinate_ ); // Draw multiple curves PathSmoothQuadraticCurvetoAbs ( const CoordinateList &coordinates_ ); // Copy constructor PathSmoothQuadraticCurvetoAbs ( const PathSmoothQuadraticCurvetoAbs& original_ ); // Destructor /*virtual*/ ~PathSmoothQuadraticCurvetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; class MagickDLLDecl PathSmoothQuadraticCurvetoRel : public VPathBase { public: // Draw a single curve PathSmoothQuadraticCurvetoRel ( const Magick::Coordinate &coordinate_ ); // Draw multiple curves PathSmoothQuadraticCurvetoRel ( const CoordinateList &coordinates_ ); // Copy constructor PathSmoothQuadraticCurvetoRel ( const PathSmoothQuadraticCurvetoRel& original_ ); // Destructor /*virtual*/ ~PathSmoothQuadraticCurvetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; // // Path Lineto // class MagickDLLDecl PathLinetoAbs : public VPathBase { public: // Draw to a single point PathLinetoAbs ( const Magick::Coordinate& coordinate_ ); // Draw to multiple points PathLinetoAbs ( const CoordinateList &coordinates_ ); // Copy constructor PathLinetoAbs ( const PathLinetoAbs& original_ ); // Destructor /*virtual*/ ~PathLinetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; class MagickDLLDecl PathLinetoRel : public VPathBase { public: // Draw to a single point PathLinetoRel ( const Magick::Coordinate& coordinate_ ); // Draw to multiple points PathLinetoRel ( const CoordinateList &coordinates_ ); // Copy constructor PathLinetoRel ( const PathLinetoRel& original_ ); // Destructor /*virtual*/ ~PathLinetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; // Path Horizontal Lineto class MagickDLLDecl PathLinetoHorizontalAbs : public VPathBase { public: PathLinetoHorizontalAbs ( double x_ ) : _x(x_) { } /*virtual*/ ~PathLinetoHorizontalAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } private: double _x; }; class MagickDLLDecl PathLinetoHorizontalRel : public VPathBase { public: PathLinetoHorizontalRel ( double x_ ) : _x(x_) { } /*virtual*/ ~PathLinetoHorizontalRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; void x( double x_ ) { _x = x_; } double x( void ) const { return _x; } private: double _x; }; // Path Vertical Lineto class MagickDLLDecl PathLinetoVerticalAbs : public VPathBase { public: PathLinetoVerticalAbs ( double y_ ) : _y(y_) { } /*virtual*/ ~PathLinetoVerticalAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _y; }; class MagickDLLDecl PathLinetoVerticalRel : public VPathBase { public: PathLinetoVerticalRel ( double y_ ) : _y(y_) { } /*virtual*/ ~PathLinetoVerticalRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; void y( double y_ ) { _y = y_; } double y( void ) const { return _y; } private: double _y; }; // Path Moveto class MagickDLLDecl PathMovetoAbs : public VPathBase { public: // Simple moveto PathMovetoAbs ( const Magick::Coordinate &coordinate_ ); // Moveto followed by implicit linetos PathMovetoAbs ( const CoordinateList &coordinates_ ); // Copy constructor PathMovetoAbs ( const PathMovetoAbs& original_ ); // Destructor /*virtual*/ ~PathMovetoAbs ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; class MagickDLLDecl PathMovetoRel : public VPathBase { public: // Simple moveto PathMovetoRel ( const Magick::Coordinate &coordinate_ ); // Moveto followed by implicit linetos PathMovetoRel ( const CoordinateList &coordinates_ ); // Copy constructor PathMovetoRel ( const PathMovetoRel& original_ ); // Destructor /*virtual*/ ~PathMovetoRel ( void ); // Operator to invoke equivalent draw API call /*virtual*/ void operator()( MagickLib::DrawContext context_ ) const; // Return polymorphic copy of object /*virtual*/ VPathBase* copy() const; private: CoordinateList _coordinates; }; #if defined(__clang__) #pragma clang diagnostic pop #endif /* if defined(__clang__) */ } // namespace Magick #endif // Magick_Drawable_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Exception.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // // Definition of Magick::Exception and derived classes // Magick::Warning* and Magick::Error*. Derived from C++ STD // 'exception' class for convenience. // // These classes form part of the Magick++ user interface. // #if !defined(Magick_Exception_header) #define Magick_Exception_header #include "Magick++/Include.h" #include #include namespace Magick { class MagickDLLDecl Exception : public std::exception { public: Exception( const std::string& what_ ); Exception( const Exception& original_ ); Exception& operator= (const Exception& original_ ); virtual const char* what () const throw(); virtual ~Exception ( ) throw (); private: std::string _what; }; // // Warnings // class MagickDLLDecl Warning : public Exception { public: explicit Warning ( const std::string& what_ ); ~Warning() throw (); }; class MagickDLLDecl WarningUndefined : public Warning { public: explicit WarningUndefined ( const std::string& what_ ); ~WarningUndefined() throw (); }; class MagickDLLDecl WarningBlob: public Warning { public: explicit WarningBlob ( const std::string& what_ ); ~WarningBlob() throw (); }; class MagickDLLDecl WarningCache: public Warning { public: explicit WarningCache ( const std::string& what_ ); ~WarningCache() throw (); }; class MagickDLLDecl WarningCoder: public Warning { public: explicit WarningCoder ( const std::string& what_ ); ~WarningCoder() throw (); }; class MagickDLLDecl WarningConfigure: public Warning { public: explicit WarningConfigure ( const std::string& what_ ); ~WarningConfigure() throw (); }; class MagickDLLDecl WarningCorruptImage: public Warning { public: explicit WarningCorruptImage ( const std::string& what_ ); ~WarningCorruptImage() throw (); }; class MagickDLLDecl WarningDelegate : public Warning { public: explicit WarningDelegate ( const std::string& what_ ); ~WarningDelegate() throw (); }; class MagickDLLDecl WarningDraw : public Warning { public: explicit WarningDraw ( const std::string& what_ ); ~WarningDraw() throw (); }; class MagickDLLDecl WarningFileOpen: public Warning { public: explicit WarningFileOpen ( const std::string& what_ ); ~WarningFileOpen() throw (); }; class MagickDLLDecl WarningImage: public Warning { public: explicit WarningImage ( const std::string& what_ ); ~WarningImage() throw (); }; class MagickDLLDecl WarningMissingDelegate : public Warning { public: explicit WarningMissingDelegate ( const std::string& what_ ); ~WarningMissingDelegate() throw (); }; class MagickDLLDecl WarningModule : public Warning { public: explicit WarningModule ( const std::string& what_ ); ~WarningModule() throw (); }; class MagickDLLDecl WarningMonitor : public Warning { public: explicit WarningMonitor ( const std::string& what_ ); ~WarningMonitor() throw (); }; class MagickDLLDecl WarningOption : public Warning { public: explicit WarningOption ( const std::string& what_ ); ~WarningOption() throw (); }; class MagickDLLDecl WarningRegistry : public Warning { public: explicit WarningRegistry ( const std::string& what_ ); ~WarningRegistry() throw (); }; class MagickDLLDecl WarningResourceLimit : public Warning { public: explicit WarningResourceLimit ( const std::string& what_ ); ~WarningResourceLimit() throw (); }; class MagickDLLDecl WarningStream : public Warning { public: explicit WarningStream ( const std::string& what_ ); ~WarningStream() throw (); }; class MagickDLLDecl WarningType : public Warning { public: explicit WarningType ( const std::string& what_ ); ~WarningType() throw (); }; class MagickDLLDecl WarningXServer : public Warning { public: explicit WarningXServer ( const std::string& what_ ); ~WarningXServer() throw (); }; // // Error exceptions // class MagickDLLDecl Error : public Exception { public: explicit Error ( const std::string& what_ ); ~Error() throw (); }; class MagickDLLDecl ErrorUndefined : public Error { public: explicit ErrorUndefined ( const std::string& what_ ); ~ErrorUndefined() throw (); }; class MagickDLLDecl ErrorBlob: public Error { public: explicit ErrorBlob ( const std::string& what_ ); ~ErrorBlob() throw (); }; class MagickDLLDecl ErrorCache: public Error { public: explicit ErrorCache ( const std::string& what_ ); ~ErrorCache() throw (); }; class MagickDLLDecl ErrorCoder: public Error { public: explicit ErrorCoder ( const std::string& what_ ); ~ErrorCoder() throw (); }; class MagickDLLDecl ErrorConfigure: public Error { public: explicit ErrorConfigure ( const std::string& what_ ); ~ErrorConfigure() throw (); }; class MagickDLLDecl ErrorCorruptImage: public Error { public: explicit ErrorCorruptImage ( const std::string& what_ ); ~ErrorCorruptImage() throw (); }; class MagickDLLDecl ErrorDelegate : public Error { public: explicit ErrorDelegate ( const std::string& what_ ); ~ErrorDelegate() throw (); }; class MagickDLLDecl ErrorDraw : public Error { public: explicit ErrorDraw ( const std::string& what_ ); ~ErrorDraw() throw (); }; class MagickDLLDecl ErrorFileOpen: public Error { public: explicit ErrorFileOpen ( const std::string& what_ ); ~ErrorFileOpen() throw (); }; class MagickDLLDecl ErrorImage: public Error { public: explicit ErrorImage ( const std::string& what_ ); ~ErrorImage() throw (); }; class MagickDLLDecl ErrorMissingDelegate : public Error { public: explicit ErrorMissingDelegate ( const std::string& what_ ); ~ErrorMissingDelegate() throw (); }; class MagickDLLDecl ErrorModule : public Error { public: explicit ErrorModule ( const std::string& what_ ); ~ErrorModule() throw (); }; class MagickDLLDecl ErrorMonitor : public Error { public: explicit ErrorMonitor ( const std::string& what_ ); ~ErrorMonitor() throw (); }; class MagickDLLDecl ErrorOption : public Error { public: explicit ErrorOption ( const std::string& what_ ); ~ErrorOption() throw (); }; class MagickDLLDecl ErrorRegistry : public Error { public: explicit ErrorRegistry ( const std::string& what_ ); ~ErrorRegistry() throw (); }; class MagickDLLDecl ErrorResourceLimit : public Error { public: explicit ErrorResourceLimit ( const std::string& what_ ); ~ErrorResourceLimit() throw (); }; class MagickDLLDecl ErrorStream : public Error { public: explicit ErrorStream ( const std::string& what_ ); ~ErrorStream() throw (); }; class MagickDLLDecl ErrorType : public Error { public: explicit ErrorType ( const std::string& what_ ); ~ErrorType() throw (); }; class MagickDLLDecl ErrorXServer : public Error { public: explicit ErrorXServer ( const std::string& what_ ); ~ErrorXServer() throw (); }; // // No user-serviceable components beyond this point. // // Throw exception based on raw data MagickDLLDeclExtern void throwExceptionExplicit( const MagickLib::ExceptionType severity_, const char* reason_, const char* description_ = 0 ); // Thow exception based on ImageMagick's ExceptionInfo MagickDLLDeclExtern void throwException( MagickLib::ExceptionInfo &exception_, const bool quiet_ = false ); } // namespace Magick #endif // Magick_Exception_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Geometry.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2014 // // Geometry Definition // // Representation of an ImageMagick geometry specification // X11 geometry specification plus hints #if !defined (Magick_Geometry_header) #define Magick_Geometry_header #include "Magick++/Include.h" #include namespace Magick { class MagickDLLDecl Geometry; // Compare two Geometry objects regardless of LHS/RHS int MagickDLLDecl operator == ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator != ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator > ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator < ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator >= ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); int MagickDLLDecl operator <= ( const Magick::Geometry& left_, const Magick::Geometry& right_ ); class MagickDLLDecl Geometry { public: Geometry ( unsigned int width_, unsigned int height_, unsigned int xOff_ = 0, unsigned int yOff_ = 0, bool xNegative_ = false, bool yNegative_ = false ); Geometry ( const std::string &geometry_ ); Geometry ( const char * geometry_ ); Geometry ( const Geometry &geometry_ ); Geometry ( ); ~Geometry ( void ); // Width void width ( unsigned int width_ ); unsigned int width ( void ) const; // Height void height ( unsigned int height_ ); unsigned int height ( void ) const; // X offset from origin void xOff ( unsigned int xOff_ ); unsigned int xOff ( void ) const; // Y offset from origin void yOff ( unsigned int yOff_ ); unsigned int yOff ( void ) const; // Sign of X offset negative? (X origin at right) void xNegative ( bool xNegative_ ); bool xNegative ( void ) const; // Sign of Y offset negative? (Y origin at bottom) void yNegative ( bool yNegative_ ); bool yNegative ( void ) const; // Width and height are expressed as percentages void percent ( bool percent_ ); bool percent ( void ) const; // Resize without preserving aspect ratio (!) void aspect ( bool aspect_ ); bool aspect ( void ) const; // Resize if image is greater than size (>) void greater ( bool greater_ ); bool greater ( void ) const; // Resize if image is less than size (<) void less ( bool less_ ); bool less ( void ) const; // Resize image to fit total pixel area specified by dimensions (@). void limitPixels ( bool limitPixels_ ); bool limitPixels ( void ) const; // Dimensions are treated as minimum rather than maximum values (^) void fillArea ( bool fillArea_ ); bool fillArea ( void ) const; // Does object contain valid geometry? void isValid ( bool isValid_ ); bool isValid ( void ) const; // Set via geometry string const Geometry& operator = ( const std::string &geometry_ ); const Geometry& operator = ( const char * geometry_ ); // Assignment operator Geometry& operator= ( const Geometry& Geometry_ ); // Return geometry string operator std::string() const; // // Public methods below this point are for Magick++ use only. // // Construct from RectangleInfo Geometry ( const MagickLib::RectangleInfo &rectangle_ ); // Return an ImageMagick RectangleInfo struct operator MagickLib::RectangleInfo() const; private: unsigned int _width; unsigned int _height; unsigned int _xOff; unsigned int _yOff; union { struct { // Bit-field for compact boolean storage bool _xNegative : 1; bool _yNegative : 1; bool _isValid : 1; bool _percent : 1; // Interpret width & height as percentages (%) bool _aspect : 1; // Force exact size (!) bool _greater : 1; // Re-size only if larger than geometry (>) bool _less : 1; // Re-size only if smaller than geometry (<) bool _limitPixels : 1;// Resize image to fit total pixel area (@). bool _fillArea : 1; // Dimensions are treated as // minimum rather than maximum // values (^) } _b; struct { // Padding for future use. unsigned int pad[2]; } _padding; } _flags; // union }; // class Geometry; } // namespace Magick // // Inlines // #endif // Magick_Geometry_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Image.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2017 // // Definition of Image, the representation of a single image in Magick++ // #if !defined(Magick_Image_header) #define Magick_Image_header #include "Magick++/Include.h" #include #include #include "Magick++/Blob.h" #include "Magick++/Color.h" #include "Magick++/Drawable.h" #include "Magick++/Exception.h" #include "Magick++/Geometry.h" #include "Magick++/TypeMetric.h" namespace Magick { // Forward declarations class Options; class ImageRef; // extern MagickDLLDecl const std::string borderGeometryDefault; // extern MagickDLLDecl const std::string frameGeometryDefault; // extern MagickDLLDecl const std::string raiseGeometryDefault; extern MagickDLLDecl const char *borderGeometryDefault; extern MagickDLLDecl const char *frameGeometryDefault; extern MagickDLLDecl const char *raiseGeometryDefault; // Compare two Image objects regardless of LHS/RHS // Image sizes and signatures are used as basis of comparison int MagickDLLDecl operator == ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator != ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator > ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator < ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator >= ( const Magick::Image& left_, const Magick::Image& right_ ); int MagickDLLDecl operator <= ( const Magick::Image& left_, const Magick::Image& right_ ); // C library initialization routine void MagickDLLDecl InitializeMagick(const char *path_); // // Image is the representation of an image. In reality, it actually // a handle object which contains a pointer to a shared reference // object (ImageRef). As such, this object is extremely space efficient. // class MagickDLLDecl Image { public: // Construct from image file or image specification Image( const std::string &imageSpec_ ); // Construct a blank image canvas of specified size and color Image( const Geometry &size_, const Color &color_ ); // Construct Image from in-memory BLOB Image ( const Blob &blob_ ); // Construct Image of specified size from in-memory BLOB Image ( const Blob &blob_, const Geometry &size_ ); // Construct Image of specified size and depth from in-memory BLOB Image ( const Blob &blob_, const Geometry &size, const unsigned int depth ); // Construct Image of specified size, depth, and format from // in-memory BLOB Image ( const Blob &blob_, const Geometry &size, const unsigned int depth_, const std::string &magick_ ); // Construct Image of specified size, and format from in-memory // BLOB Image ( const Blob &blob_, const Geometry &size, const std::string &magick_ ); // Construct an image based on an array of raw pixels, of // specified type and mapping, in memory Image ( const unsigned int width_, const unsigned int height_, const std::string &map_, const StorageType type_, const void *pixels_ ); // Default constructor Image( void ); // Destructor virtual ~Image(); /// Copy constructor Image ( const Image & image_ ); // Assignment operator Image& operator= ( const Image &image_ ); ////////////////////////////////////////////////////////////////////// // // Image operations // ////////////////////////////////////////////////////////////////////// // Local adaptive threshold image // http://www.dai.ed.ac.uk/HIPR2/adpthrsh.htm // Width x height define the size of the pixel neighborhood // offset = constant to subtract from pixel neighborhood mean void adaptiveThreshold ( const unsigned int width, const unsigned int height, const double offset = 0.0 ); void adaptiveThreshold ( const unsigned int width, const unsigned int height, const unsigned int offset) MAGICK_FUNC_DEPRECATED; // Add noise to image with specified noise type void addNoise ( const NoiseType noiseType_ ); void addNoiseChannel ( const ChannelType channel_, const NoiseType noiseType_); // Transform image by specified affine (or free transform) matrix. void affineTransform ( const DrawableAffine &affine ); // // Annotate image (draw text on image) // // Gravity effects text placement in bounding area according to rules: // NorthWestGravity text bottom-left corner placed at top-left // NorthGravity text bottom-center placed at top-center // NorthEastGravity text bottom-right corner placed at top-right // WestGravity text left-center placed at left-center // CenterGravity text center placed at center // EastGravity text right-center placed at right-center // SouthWestGravity text top-left placed at bottom-left // SouthGravity text top-center placed at bottom-center // SouthEastGravity text top-right placed at bottom-right // Annotate using specified text, and placement location void annotate ( const std::string &text_, const Geometry &location_ ); // Annotate using specified text, bounding area, and placement // gravity void annotate ( const std::string &text_, const Geometry &boundingArea_, const GravityType gravity_ ); // Annotate with text using specified text, bounding area, // placement gravity, and rotation. void annotate ( const std::string &text_, const Geometry &boundingArea_, const GravityType gravity_, const double degrees_ ); // Annotate with text (bounding area is entire image) and placement // gravity. void annotate ( const std::string &text_, const GravityType gravity_ ); // Orient image to be right-side up based on its current // orientation attribute. This allows the image to be viewed // correctly when the orientation attribute is not available, or // is not respected. void autoOrient( void ); // Blur image with specified blur factor // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. void blur ( const double radius_ = 0.0, const double sigma_ = 1.0 ); void blurChannel ( const ChannelType channel_, const double radius_ = 0.0, const double sigma_ = 1.0 ); // Border image (add border to image) void border ( const Geometry &geometry_ = borderGeometryDefault ); // Bake in the ASC-CDL, which is a convention for the for the // exchange of basic primary color grading information between for // the exchange of basic primary color grading information between // equipment and software from different manufacturers. It is a // useful transform for other purposes as well. void cdl ( const std::string &cdl_ ); // Extract channel from image void channel ( const ChannelType channel_ ); // Set or obtain modulus channel depth void channelDepth ( const ChannelType channel_, const unsigned int depth_ ); unsigned int channelDepth ( const ChannelType channel_ ); // Charcoal effect image (looks like charcoal sketch) // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. void charcoal ( const double radius_ = 0.0, const double sigma_ = 1.0 ); // Chop image (remove vertical or horizontal subregion of image) // FIXME: describe how geometry argument is used to select either // horizontal or vertical subregion of image. void chop ( const Geometry &geometry_ ); // Colorize image with pen color, using specified percent opacity // for red, green, and blue quantums void colorize ( const unsigned int opacityRed_, const unsigned int opacityGreen_, const unsigned int opacityBlue_, const Color &penColor_ ); // Colorize image with pen color, using specified percent opacity. void colorize ( const unsigned int opacity_, const Color &penColor_ ); // Apply a color matrix to the image channels. The user supplied // matrix may be of order 1 to 5 (1x1 through 5x5). void colorMatrix (const unsigned int order_, const double *color_matrix_); // Comment image (add comment string to image) void comment ( const std::string &comment_ ); // Compare current image with another image // Sets meanErrorPerPixel, normalizedMaxError, and normalizedMeanError // in the current image. False is returned if the images are identical. bool compare ( const Image &reference_ ); // Compose an image onto another at specified offset and using // specified algorithm void composite ( const Image &compositeImage_, const int xOffset_, const int yOffset_, const CompositeOperator compose_ = InCompositeOp ); void composite ( const Image &compositeImage_, const Geometry &offset_, const CompositeOperator compose_ = InCompositeOp ); void composite ( const Image &compositeImage_, const GravityType gravity_, const CompositeOperator compose_ = InCompositeOp ); // Contrast image (enhance intensity differences in image) void contrast ( const unsigned int sharpen_ ); // Convolve image. Applies a user-specified convolution to the image. // order_ represents the number of columns and rows in the filter kernel. // kernel_ is an array of doubles representing the convolution kernel. void convolve ( const unsigned int order_, const double *kernel_ ); // Crop image (subregion of original image) void crop ( const Geometry &geometry_ ); // Cycle image colormap void cycleColormap ( const int amount_ ); // Despeckle image (reduce speckle noise) void despeckle ( void ); // Display image on screen void display ( void ); // Draw on image using a single drawable void draw ( const Drawable &drawable_ ); // Draw on image using a drawable list void draw ( const std::list &drawable_ ); // Edge image (hilight edges in image) void edge ( const double radius_ = 0.0 ); // Emboss image (hilight edges with 3D effect) // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. void emboss ( const double radius_ = 0.0, const double sigma_ = 1.0); // Enhance image (minimize noise) void enhance ( void ); // Equalize image (histogram equalization) void equalize ( void ); // Erase image to current "background color" void erase ( void ); // Create an image canvas using background color sized according // to geometry and composite existing image on it, with image // placement controlled by gravity. Parameters are obtained from // existing image properties if they are not specified via a // method parameter. Parameters which are supported by image // properties (gravity and backgroundColor) update those image // properties as a side-effect. void extent ( const Geometry &geometry_ ); void extent ( const Geometry &geometry_, const GravityType &gravity_ ); void extent ( const Geometry &geometry_, const Color &backgroundColor_ ); void extent ( const Geometry &geometry_, const Color &backgroundColor_, const GravityType &gravity_ ); // Flip image (reflect each scanline in the vertical direction) void flip ( void ); // Flood-fill color across pixels that match the color of the // target pixel and are neighbors of the target pixel. // Uses current fuzz setting when determining color match. void floodFillColor( const unsigned int x_, const unsigned int y_, const Color &fillColor_ ); void floodFillColor( const Geometry &point_, const Color &fillColor_ ); // Flood-fill color across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. void floodFillColor( const unsigned int x_, const unsigned int y_, const Color &fillColor_, const Color &borderColor_ ); void floodFillColor( const Geometry &point_, const Color &fillColor_, const Color &borderColor_ ); // Floodfill pixels matching color (within fuzz factor) of target // pixel(x,y) with replacement opacity value using method. void floodFillOpacity ( const unsigned int x_, const unsigned int y_, const unsigned int opacity_, const PaintMethod method_ ); // Flood-fill texture across pixels that match the color of the // target pixel and are neighbors of the target pixel. // Uses current fuzz setting when determining color match. void floodFillTexture( const unsigned int x_, const unsigned int y_, const Image &texture_ ); void floodFillTexture( const Geometry &point_, const Image &texture_ ); // Flood-fill texture across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. void floodFillTexture( const unsigned int x_, const unsigned int y_, const Image &texture_, const Color &borderColor_ ); void floodFillTexture( const Geometry &point_, const Image &texture_, const Color &borderColor_ ); // Flop image (reflect each scanline in the horizontal direction) void flop ( void ); // Frame image void frame ( const Geometry &geometry_ = frameGeometryDefault ); void frame ( const unsigned int width_, const unsigned int height_, const int innerBevel_ = 6, const int outerBevel_ = 6 ); // Gamma correct image void gamma ( const double gamma_ ); void gamma ( const double gammaRed_, const double gammaGreen_, const double gammaBlue_ ); // Gaussian blur image // The number of neighbor pixels to be included in the convolution // mask is specified by 'width_'. The standard deviation of the // gaussian bell curve is specified by 'sigma_'. void gaussianBlur ( const double width_, const double sigma_ ); void gaussianBlurChannel ( const ChannelType channel_, const double width_, const double sigma_ ); // Implode image (special effect) void implode ( const double factor_ ); // Apply a color lookup table (Hald CLUT) to the image. void haldClut ( const Image &clutImage_ ); // Label image void label ( const std::string &label_ ); // Level image. Adjust the levels of the image by scaling the // colors falling between specified white and black points to the // full available quantum range. The parameters provided represent // the black, mid (gamma), and white points. The black point // specifies the darkest color in the image. Colors darker than // the black point are set to zero. Mid point (gamma) specifies a // gamma correction to apply to the image. White point specifies // the lightest color in the image. Colors brighter than the // white point are set to the maximum quantum value. The black and // white point have the valid range 0 to MaxRGB while mid (gamma) // has a useful range of 0 to ten. void level ( const double black_point, const double white_point, const double mid_point=1.0 ); // Level image channel. Adjust the levels of the image channel by // scaling the values falling between specified white and black // points to the full available quantum range. The parameters // provided represent the black, mid (gamma), and white points. // The black point specifies the darkest color in the // image. Colors darker than the black point are set to zero. Mid // point (gamma) specifies a gamma correction to apply to the // image. White point specifies the lightest color in the image. // Colors brighter than the white point are set to the maximum // quantum value. The black and white point have the valid range 0 // to MaxRGB while mid (gamma) has a useful range of 0 to ten. void levelChannel ( const ChannelType channel, const double black_point, const double white_point, const double mid_point=1.0 ); // Magnify image by integral size void magnify ( void ); // Remap image colors with closest color from reference image void map ( const Image &mapImage_ , const bool dither_ = false ); // Floodfill designated area with replacement opacity value void matteFloodfill ( const Color &target_ , const unsigned int opacity_, const int x_, const int y_, const PaintMethod method_ ); // Filter image by replacing each pixel component with the median // color in a circular neighborhood void medianFilter ( const double radius_ = 0.0 ); // Reduce image by integral size void minify ( void ); // Modulate percent hue, saturation, and brightness of an image. // Modulation of saturation and brightness is as a ratio of the // current value (1.0 for no change). Modulation of hue is an // absolute rotation of -180 degrees to +180 degrees from the // current position corresponding to an argument range of 0 to 2.0 // (1.0 for no change). void modulate ( const double brightness_, const double saturation_, const double hue_ ); // Motion blur image with specified blur factor // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. // The angle_ parameter specifies the angle the object appears // to be comming from (zero degrees is from the right). void motionBlur ( const double radius_, const double sigma_, const double angle_ ); // Negate colors in image. Set grayscale to only negate grayscale // values in image. void negate ( const bool grayscale_ = false ); // Normalize image (increase contrast by normalizing the pixel // values to span the full range of color values) void normalize ( void ); // Oilpaint image (image looks like oil painting) void oilPaint ( const double radius_ = 3.0 ); // Set or attenuate the opacity channel in the image. If the image // pixels are opaque then they are set to the specified opacity // value, otherwise they are blended with the supplied opacity // value. The value of opacity_ ranges from 0 (completely opaque) // to MaxRGB. The defines OpaqueOpacity and TransparentOpacity are // available to specify completely opaque or completely // transparent, respectively. void opacity ( const unsigned int opacity_ ); // Change color of opaque pixel to specified pen color. void opaque ( const Color &opaqueColor_, const Color &penColor_ ); // Ping is similar to read except only enough of the image is read // to determine the image columns, rows, and filesize. Access the // columns(), rows(), and fileSize() attributes after invoking // ping. The image data is not valid after calling ping. void ping ( const std::string &imageSpec_ ); // Ping is similar to read except only enough of the image is read // to determine the image columns, rows, and filesize. Access the // columns(), rows(), and fileSize() attributes after invoking // ping. The image data is not valid after calling ping. void ping ( const Blob &blob_ ); // Quantize image (reduce number of colors) void quantize ( const bool measureError_ = false ); // Apply an arithmetic or bitwise operator to the image pixel quantums. void quantumOperator ( const ChannelType channel_, const QuantumOperator operator_, Quantum rvalue_) MAGICK_FUNC_DEPRECATED; void quantumOperator ( const ChannelType channel_, const QuantumOperator operator_, double rvalue_); void quantumOperator ( const int x_,const int y_, const unsigned int columns_, const unsigned int rows_, const ChannelType channel_, const QuantumOperator operator_, const Quantum rvalue_) MAGICK_FUNC_DEPRECATED; void quantumOperator ( const int x_,const int y_, const unsigned int columns_, const unsigned int rows_, const ChannelType channel_, const QuantumOperator operator_, const double rvalue_); // Execute a named process module using an argc/argv syntax similar to // that accepted by a C 'main' routine. An exception is thrown if the // requested process module doesn't exist, fails to load, or fails during // execution. void process ( std::string name_, const int argc_, char **argv_ ); // Raise image (lighten or darken the edges of an image to give a // 3-D raised or lowered effect) void raise ( const Geometry &geometry_ = raiseGeometryDefault, const bool raisedFlag_ = false ); // Random threshold image. // // Changes the value of individual pixels based on the intensity // of each pixel compared to a random threshold. The result is a // low-contrast, two color image. The thresholds_ argument is a // geometry containing LOWxHIGH thresholds. If the string // contains 2x2, 3x3, or 4x4, then an ordered dither of order 2, // 3, or 4 will be performed instead. If a channel_ argument is // specified then only the specified channel is altered. This is // a very fast alternative to 'quantize' based dithering. void randomThreshold( const Geometry &thresholds_ ); void randomThresholdChannel( const Geometry &thresholds_, const ChannelType channel_ ); // Read single image frame into current object void read ( const std::string &imageSpec_ ); // Read single image frame of specified size into current object void read ( const Geometry &size_, const std::string &imageSpec_ ); // Read single image frame from in-memory BLOB void read ( const Blob &blob_ ); // Read single image frame of specified size from in-memory BLOB void read ( const Blob &blob_, const Geometry &size_ ); // Read single image frame of specified size and depth from // in-memory BLOB void read ( const Blob &blob_, const Geometry &size_, const unsigned int depth_ ); // Read single image frame of specified size, depth, and format // from in-memory BLOB void read ( const Blob &blob_, const Geometry &size_, const unsigned int depth_, const std::string &magick_ ); // Read single image frame of specified size, and format from // in-memory BLOB void read ( const Blob &blob_, const Geometry &size_, const std::string &magick_ ); // Read single image frame from an array of raw pixels, with // specified storage type (ConstituteImage), e.g. // image.read( 640, 480, "RGB", 0, pixels ); void read ( const unsigned int width_, const unsigned int height_, const std::string &map_, const StorageType type_, const void *pixels_ ); // Reduce noise in image using a noise peak elimination filter void reduceNoise ( void ); void reduceNoise ( const double order_ ); // Resets the image page canvas and position. void repage(); // Resize image, specifying geometry, filter, and blur void resize ( const Geometry &geometry_, const FilterTypes filterType_, const double blur_ ); // Resize image, specifying geometry and filter, with blur using // Image default. void resize ( const Geometry &geometry_, const FilterTypes filterType_ ); // Resize image, specifying only geometry, with filter and blur // obtained from Image default. Same result as 'zoom' method. void resize ( const Geometry &geometry_ ); // Roll image (rolls image vertically and horizontally) by specified // number of columnms and rows) void roll ( const Geometry &roll_ ); void roll ( const unsigned int columns_, const unsigned int rows_ ); // Rotate image counter-clockwise by specified number of degrees. void rotate ( const double degrees_ ); // Resize image by using pixel sampling algorithm void sample ( const Geometry &geometry_ ); // Resize image by using simple ratio algorithm void scale ( const Geometry &geometry_ ); // Resize image using several algorithms to make smaller images // very quickly. void thumbnail ( const Geometry &geometry_ ); // Segment (coalesce similar image components) by analyzing the // histograms of the color components and identifying units that // are homogeneous with the fuzzy c-means technique. Also uses // QuantizeColorSpace and Verbose image attributes void segment ( const double clusterThreshold_ = 1.0, const double smoothingThreshold_ = 1.5 ); // Shade image using distant light source void shade ( const double azimuth_ = 30, const double elevation_ = 30, const bool colorShading_ = false ); // Sharpen pixels in image // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. void sharpen ( const double radius_ = 0.0, const double sigma_ = 1.0 ); void sharpenChannel ( const ChannelType channel_, const double radius_ = 0.0, const double sigma_ = 1.0 ); // Shave pixels from image edges. void shave ( const Geometry &geometry_ ); // Shear image (create parallelogram by sliding image by X or Y axis) void shear ( const double xShearAngle_, const double yShearAngle_ ); // Solarize image (similar to effect seen when exposing a // photographic film to light during the development process) void solarize ( const double factor_ = 50.0 ); // Spread pixels randomly within image by specified ammount void spread ( const unsigned int amount_ = 3 ); // Add a digital watermark to the image (based on second image) void stegano ( const Image &watermark_ ); // Create an image which appears in stereo when viewed with // red-blue glasses (Red image on left, blue on right) void stereo ( const Image &rightImage_ ); // Remove all profiles and text attributes from the image. void strip ( void ); // Swirl image (image pixels are rotated by degrees) void swirl ( const double degrees_ ); // Channel a texture on image background void texture ( const Image &texture_ ); // Threshold image channels (below threshold becomes black, above // threshold becomes white). // The range of the threshold parameter is 0 to MaxRGB. void threshold ( const double threshold_ ); // Transform image based on image and crop geometries // Crop geometry is optional void transform ( const Geometry &imageGeometry_ ); void transform ( const Geometry &imageGeometry_, const Geometry &cropGeometry_ ); // Add matte image to image, setting pixels matching color to // transparent void transparent ( const Color &color_ ); // Trim edges that are the background color from the image void trim ( void ); // Image representation type (also see type attribute) // Available types: // Bilevel Grayscale GrayscaleMatte // Palette PaletteMatte TrueColor // TrueColorMatte ColorSeparation ColorSeparationMatte void type ( const ImageType type_ ); // Replace image with a sharpened version of the original image // using the unsharp mask algorithm. // radius_ // the radius of the Gaussian, in pixels, not counting the // center pixel. // sigma_ // the standard deviation of the Gaussian, in pixels. // amount_ // the percentage of the difference between the original and // the blur image that is added back into the original. // threshold_ // the threshold in pixels needed to apply the diffence amount. void unsharpmask ( const double radius_, const double sigma_, const double amount_, const double threshold_ ); void unsharpmaskChannel ( const ChannelType channel_, const double radius_, const double sigma_, const double amount_, const double threshold_ ); // Map image pixels to a sine wave void wave ( const double amplitude_ = 25.0, const double wavelength_ = 150.0 ); // Write single image frame to a file void write ( const std::string &imageSpec_ ); // Write single image frame to in-memory BLOB, with optional // format and adjoin parameters. void write ( Blob *blob_ ); void write ( Blob *blob_, const std::string &magick_ ); void write ( Blob *blob_, const std::string &magick_, const unsigned int depth_ ); // Write single image frame to an array of pixels with storage // type specified by user (DispatchImage), e.g. // image.write( 0, 0, 640, 1, "RGB", 0, pixels ); void write ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_, const std::string& map_, const StorageType type_, void *pixels_ ); // Zoom image to specified size. void zoom ( const Geometry &geometry_ ); ////////////////////////////////////////////////////////////////////// // // Image Attributes and Options // ////////////////////////////////////////////////////////////////////// // Join images into a single multi-image file void adjoin ( const bool flag_ ); bool adjoin ( void ) const; // Anti-alias Postscript and TrueType fonts (default true) void antiAlias( const bool flag_ ); bool antiAlias( void ); // Time in 1/100ths of a second which must expire before // displaying the next image in an animated sequence. void animationDelay ( const unsigned int delay_ ); unsigned int animationDelay ( void ) const; // Number of iterations to loop an animation (e.g. Netscape loop // extension) for. void animationIterations ( const unsigned int iterations_ ); unsigned int animationIterations ( void ) const; // Access/Update a named image text attribute. Updates append the // provided to any existing attribute text. Pass NULL as the // value to remove an existing value or before a subsequent call // to add new text. void attribute ( const std::string name_, const char * value_ ); void attribute ( const std::string name_, const std::string value_ ); std::string attribute ( const std::string name_ ); // Image background color void backgroundColor ( const Color &color_ ); Color backgroundColor ( void ) const; // Name of texture image to tile onto the image background void backgroundTexture (const std::string &backgroundTexture_ ); std::string backgroundTexture ( void ) const; // Base image width (before transformations) unsigned int baseColumns ( void ) const; // Base image filename (before transformations) std::string baseFilename ( void ) const; // Base image height (before transformations) unsigned int baseRows ( void ) const; // Image border color void borderColor ( const Color &color_ ); Color borderColor ( void ) const; // Return smallest bounding box enclosing non-border pixels. The // current fuzz value is used when discriminating between pixels. // This is the crop bounding box used by crop(Geometry(0,0)); Geometry boundingBox ( void ) const; // Text bounding-box base color (default none) void boxColor ( const Color &boxColor_ ); Color boxColor ( void ) const; // Pixel cache threshold in megabytes. Once this memory threshold // is exceeded, all subsequent pixels cache operations are to/from // disk. This setting is shared by all Image objects. static void cacheThreshold ( const unsigned int threshold_ ); // Chromaticity blue primary point (e.g. x=0.15, y=0.06) void chromaBluePrimary ( const double x_, const double y_ ); void chromaBluePrimary ( double *x_, double *y_ ) const; // Chromaticity green primary point (e.g. x=0.3, y=0.6) void chromaGreenPrimary ( const double x_, const double y_ ); void chromaGreenPrimary ( double *x_, double *y_ ) const; // Chromaticity red primary point (e.g. x=0.64, y=0.33) void chromaRedPrimary ( const double x_, const double y_ ); void chromaRedPrimary ( double *x_, double *y_ ) const; // Chromaticity white point (e.g. x=0.3127, y=0.329) void chromaWhitePoint ( const double x_, const double y_ ); void chromaWhitePoint ( double *x_, double *y_ ) const; // Image class (DirectClass or PseudoClass) // NOTE: setting a DirectClass image to PseudoClass will result in // the loss of color information if the number of colors in the // image is greater than the maximum palette size (either 256 or // 65536 entries depending on the value of QuantumDepth when // ImageMagick was built). void classType ( const ClassType class_ ); ClassType classType ( void ) const; // Associate a clip mask with the image. The clip mask must be the // same dimensions as the image. Pass an invalid image to unset an // existing clip mask. void clipMask ( const Image & clipMask_ ); Image clipMask ( void ) const; // Colors within this distance are considered equal void colorFuzz ( const double fuzz_ ); double colorFuzz ( void ) const; // Color at colormap position index_ void colorMap ( const unsigned int index_, const Color &color_ ); Color colorMap ( const unsigned int index_ ) const; // Colormap size (number of colormap entries) void colorMapSize ( const unsigned int entries_ ); unsigned int colorMapSize ( void ); // Image Color Space void colorSpace( const ColorspaceType colorSpace_ ); ColorspaceType colorSpace ( void ) const; // Image width unsigned int columns ( void ) const; // Image comment std::string comment ( void ) const; // Composition operator to be used when composition is implicitly // used (such as for image flattening). void compose (const CompositeOperator compose_); CompositeOperator compose ( void ) const; // Compression type void compressType ( const CompressionType compressType_ ); CompressionType compressType ( void ) const; // Enable printing of debug messages from ImageMagick void debug ( const bool flag_ ); bool debug ( void ) const; // Tagged image format define (set/access coder-specific option) The // magick_ option specifies the coder the define applies to. The key_ // option provides the key specific to that coder. The value_ option // provides the value to set (if any). See the defineSet() method if the // key must be removed entirely. void defineValue ( const std::string &magick_, const std::string &key_, const std::string &value_ ); std::string defineValue ( const std::string &magick_, const std::string &key_ ) const; // Tagged image format define. Similar to the defineValue() method // except that passing the flag_ value 'true' creates a value-less // define with that format and key. Passing the flag_ value 'false' // removes any existing matching definition. The method returns 'true' // if a matching key exists, and 'false' if no matching key exists. void defineSet ( const std::string &magick_, const std::string &key_, bool flag_ ); bool defineSet ( const std::string &magick_, const std::string &key_ ) const; // Vertical and horizontal resolution in pixels of the image // // The resolution is expressed in resolution units as supported by // the resolutionUnits() method. // // Please note that the underlying resolution is floating point // and use of this method will result in rounding floating point // value to integer vaues. Use the xResolution() and // yResolution() methods when full accuracy is required. void density ( const Geometry &geomery_ ); Geometry density ( void ) const; // Image depth (bits allocated to red/green/blue components) void depth ( const unsigned int depth_ ); unsigned int depth ( void ) const; // Tile names from within an image montage std::string directory ( void ) const; // Endianness (little like Intel or big like SPARC) for image // formats which support endian-specific options. void endian ( const EndianType endian_ ); EndianType endian ( void ) const; // Image file name void fileName ( const std::string &fileName_ ); std::string fileName ( void ) const; // Number of bytes of the image on disk off_t fileSize ( void ) const; // Color to use when filling drawn objects void fillColor ( const Color &fillColor_ ); Color fillColor ( void ) const; // Rule to use when filling drawn objects void fillRule ( const FillRule &fillRule_ ); FillRule fillRule ( void ) const; // Pattern to use while filling drawn objects. void fillPattern ( const Image &fillPattern_ ); Image fillPattern ( void ) const; // Filter to use when resizing image using 'zoom' or 'resize'. void filterType ( const FilterTypes filterType_ ); FilterTypes filterType ( void ) const; // Text rendering font void font ( const std::string &font_ ); std::string font ( void ) const; // Font point size void fontPointsize ( const double pointSize_ ); double fontPointsize ( void ) const; // Obtain font metrics for text string given current font, // pointsize, and density settings. void fontTypeMetrics( const std::string &text_, TypeMetric *metrics ); // Long image format description std::string format ( void ) const; // Format the specified expression similar to command line '-format'. // For example "%wx%h" is converted to a string containing image // WIDTHxHEIGHT like "640x480". std::string formatExpression( const std::string expression ); // Gamma level of the image double gamma ( void ) const; // Preferred size of the image when encoding Geometry geometry ( void ) const; // GIF disposal method void gifDisposeMethod ( const unsigned int disposeMethod_ ); unsigned int gifDisposeMethod ( void ) const; // ICC color profile (BLOB) void iccColorProfile( const Blob &colorProfile_ ); Blob iccColorProfile( void ) const; // Type of interlacing to use void interlaceType ( const InterlaceType interlace_ ); InterlaceType interlaceType ( void ) const; // IPTC profile (BLOB) void iptcProfile( const Blob& iptcProfile_ ); Blob iptcProfile( void ) const; // Does object contain valid image? void isValid ( const bool isValid_ ); bool isValid ( void ) const; // Image label std::string label ( void ) const; // Stroke width for drawing vector objects (default one) // This method is now deprecated. Please use strokeWidth instead. void lineWidth ( const double lineWidth_ ); double lineWidth ( void ) const; // File type magick identifier (.e.g "GIF") void magick ( const std::string &magick_ ); std::string magick ( void ) const; // Image supports transparency (matte channel) void matte ( const bool matteFlag_ ); bool matte ( void ) const; // Transparent color void matteColor ( const Color &matteColor_ ); Color matteColor ( void ) const; // The mean error per pixel computed when an image is color reduced double meanErrorPerPixel ( void ) const; // Image modulus depth (minimum number of bits required to support // red/green/blue components without loss of accuracy) void modulusDepth ( const unsigned int modulusDepth_ ); unsigned int modulusDepth ( void ) const; // Tile size and offset within an image montage Geometry montageGeometry ( void ) const; // Transform image to black and white void monochrome ( const bool monochromeFlag_ ); bool monochrome ( void ) const; // The normalized max error per pixel computed when an image is // color reduced. double normalizedMaxError ( void ) const; // The normalized mean error per pixel computed when an image is // color reduced. double normalizedMeanError ( void ) const; // Image orientation void orientation ( const OrientationType orientation_ ); OrientationType orientation ( void ) const; // Preferred size and location of an image canvas. void page ( const Geometry &pageSize_ ); Geometry page ( void ) const; // Pen color (deprecated, don't use any more) void penColor ( const Color &penColor_ ); Color penColor ( void ) const; // Pen texture image (deprecated, don't use any more) void penTexture ( const Image &penTexture_ ); Image penTexture ( void ) const; // Get/set pixel color at location x & y. void pixelColor ( const unsigned int x_, const unsigned int y_, const Color &color_ ); Color pixelColor ( const unsigned int x_, const unsigned int y_ ) const; // Add or remove a named profile to/from the image. Remove the // profile by passing an empty Blob (e.g. Blob()). Valid names are // "*", "8BIM", "ICM", "IPTC", or a user/format-defined profile name. void profile( const std::string name_, const Blob &colorProfile_ ); // Retrieve a named profile from the image. Valid names are: // "8BIM", "8BIMTEXT", "APP1", "APP1JPEG", "ICC", "ICM", & "IPTC" // or an existing user/format-defined profile name. Blob profile( const std::string name_ ) const; // JPEG/MIFF/PNG compression level (default 75). void quality ( const unsigned int quality_ ); unsigned int quality ( void ) const; // Maximum number of colors to quantize to void quantizeColors ( const unsigned int colors_ ); unsigned int quantizeColors ( void ) const; // Colorspace to quantize in. void quantizeColorSpace ( const ColorspaceType colorSpace_ ); ColorspaceType quantizeColorSpace ( void ) const; // Dither image during quantization (default true). void quantizeDither ( const bool ditherFlag_ ); bool quantizeDither ( void ) const; // Quantization tree-depth void quantizeTreeDepth ( const unsigned int treeDepth_ ); unsigned int quantizeTreeDepth ( void ) const; // Suppress all warning messages. Error messages are still reported. void quiet ( const bool quiet_ ); bool quiet ( void ) const; // The type of rendering intent void renderingIntent ( const RenderingIntent renderingIntent_ ); RenderingIntent renderingIntent ( void ) const; // Units of image resolution void resolutionUnits ( const ResolutionType resolutionUnits_ ); ResolutionType resolutionUnits ( void ) const; // The number of pixel rows in the image unsigned int rows ( void ) const; // Image scene number void scene ( const unsigned int scene_ ); unsigned int scene ( void ) const; // Image signature. Set force_ to true in order to re-calculate // the signature regardless of whether the image data has been // modified. std::string signature ( const bool force_ = false ) const; // Width and height of a raw image void size ( const Geometry &geometry_ ); Geometry size ( void ) const; // Obtain image statistics. Statistics are normalized to the range // of 0.0 to 1.0 and are output to the specified ImageStatistics // structure. void statistics ( ImageStatistics *statistics ) const; // enabled/disable stroke anti-aliasing void strokeAntiAlias( const bool flag_ ); bool strokeAntiAlias( void ) const; // Color to use when drawing object outlines void strokeColor ( const Color &strokeColor_ ); Color strokeColor ( void ) const; // Specify the pattern of dashes and gaps used to stroke // paths. The strokeDashArray represents a zero-terminated array // of numbers that specify the lengths of alternating dashes and // gaps in pixels. If an odd number of values is provided, then // the list of values is repeated to yield an even number of // values. A typical strokeDashArray_ array might contain the // members 5 3 2 0, where the zero value indicates the end of the // pattern array. void strokeDashArray ( const double* strokeDashArray_ ); const double* strokeDashArray ( void ) const; // While drawing using a dash pattern, specify distance into the // dash pattern to start the dash (default 0). void strokeDashOffset ( const double strokeDashOffset_ ); double strokeDashOffset ( void ) const; // Specify the shape to be used at the end of open subpaths when // they are stroked. Values of LineCap are UndefinedCap, ButtCap, // RoundCap, and SquareCap. void strokeLineCap ( const LineCap lineCap_ ); LineCap strokeLineCap ( void ) const; // Specify the shape to be used at the corners of paths (or other // vector shapes) when they are stroked. Values of LineJoin are // UndefinedJoin, MiterJoin, RoundJoin, and BevelJoin. void strokeLineJoin ( const LineJoin lineJoin_ ); LineJoin strokeLineJoin ( void ) const; // Specify miter limit. When two line segments meet at a sharp // angle and miter joins have been specified for 'lineJoin', it is // possible for the miter to extend far beyond the thickness of // the line stroking the path. The miterLimit' imposes a limit on // the ratio of the miter length to the 'lineWidth'. The default // value of this parameter is 4. void strokeMiterLimit ( const unsigned int miterLimit_ ); unsigned int strokeMiterLimit ( void ) const; // Pattern image to use while stroking object outlines. void strokePattern ( const Image &strokePattern_ ); Image strokePattern ( void ) const; // Stroke width for drawing vector objects (default one) void strokeWidth ( const double strokeWidth_ ); double strokeWidth ( void ) const; // Subimage of an image sequence void subImage ( const unsigned int subImage_ ); unsigned int subImage ( void ) const; // Number of images relative to the base image void subRange ( const unsigned int subRange_ ); unsigned int subRange ( void ) const; // Annotation text encoding (e.g. "UTF-16") void textEncoding ( const std::string &encoding_ ); std::string textEncoding ( void ) const; // Tile name void tileName ( const std::string &tileName_ ); std::string tileName ( void ) const; // Number of colors in the image unsigned long totalColors ( void ); // Origin of coordinate system to use when annotating with text or drawing void transformOrigin ( const double x_,const double y_ ); // Rotation to use when annotating with text or drawing void transformRotation ( const double angle_ ); // Reset transformation parameters to default void transformReset ( void ); // Scale to use when annotating with text or drawing void transformScale ( const double sx_, const double sy_ ); // Skew to use in X axis when annotating with text or drawing void transformSkewX ( const double skewx_ ); // Skew to use in Y axis when annotating with text or drawing void transformSkewY ( const double skewy_ ); // Image representation type (also see type operation) // Available types: // Bilevel Grayscale GrayscaleMatte // Palette PaletteMatte TrueColor // TrueColorMatte ColorSeparation ColorSeparationMatte ImageType type ( void ) const; // Print detailed information about the image void verbose ( const bool verboseFlag_ ); bool verbose ( void ) const; // FlashPix viewing parameters void view ( const std::string &view_ ); std::string view ( void ) const; // X11 display to display to, obtain fonts from, or to capture // image from void x11Display ( const std::string &display_ ); std::string x11Display ( void ) const; // x resolution of the image void xResolution ( const double x_resolution ); double xResolution ( void ) const; // y resolution of the image void yResolution ( const double y_resolution ); double yResolution ( void ) const; ////////////////////////////////////////////////////////////////////// // // Low-level Pixel Access Routines // // Also see the Pixels class, which provides support for multiple // cache views. // ////////////////////////////////////////////////////////////////////// // Transfers read-only pixels from the image to the pixel cache as // defined by the specified region const PixelPacket* getConstPixels ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ) const; // Obtain mutable image pixel indexes (valid for PseudoClass images) IndexPacket* getIndexes ( void ); // Obtain immutable image pixel indexes (valid for PseudoClass images) const IndexPacket* getConstIndexes ( void ) const; // Transfers pixels from the image to the pixel cache as defined // by the specified region. Modified pixels may be subsequently // transferred back to the image via syncPixels. This method is // valid for DirectClass images. PixelPacket* getPixels ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ); // Allocates a pixel cache region to store image pixels as defined // by the region rectangle. This area is subsequently transferred // from the pixel cache to the image via syncPixels. PixelPacket* setPixels ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ); // Transfers the image cache pixels to the image. void syncPixels ( void ); // Transfers one or more pixel components from a buffer or file // into the image pixel cache of an image. // Used to support image decoders. void readPixels ( const QuantumType quantum_, const unsigned char *source_ ); // Transfers one or more pixel components from the image pixel // cache to a buffer or file. // Used to support image encoders. void writePixels ( const QuantumType quantum_, unsigned char *destination_ ); ////////////////////////////////////////////////////////////////////// // // No user-serviceable parts beyond this point // ////////////////////////////////////////////////////////////////////// // Construct with MagickLib::Image and default options Image ( MagickLib::Image* image_ ); // Retrieve Image* MagickLib::Image*& image( void ); const MagickLib::Image* constImage( void ) const; // Retrieve Options* Options* options( void ); const Options* constOptions( void ) const; // Retrieve ImageInfo* MagickLib::ImageInfo * imageInfo( void ); const MagickLib::ImageInfo * constImageInfo( void ) const; // Retrieve QuantizeInfo* MagickLib::QuantizeInfo * quantizeInfo( void ); const MagickLib::QuantizeInfo * constQuantizeInfo( void ) const; // Replace current image (reference counted) MagickLib::Image* replaceImage ( MagickLib::Image* replacement_ ); // Prepare to update image (copy if reference > 1) void modifyImage ( void ); // Test for ImageMagick error and throw exception if error void throwImageException( void ) const; // Register image with image registry or obtain registration id long registerId( void ); // Unregister image from image registry void unregisterId( void) ; private: void throwImageException( MagickLib::ExceptionInfo &exception_ ) const; ImageRef * _imgRef; }; } // end of namespace Magick // // Inlines // // // Image // // Reduce noise in image using a noise peak elimination filter inline void Magick::Image::reduceNoise ( void ) { reduceNoise( 3.0 ); } // Stroke width for drawing vector objects (default one) inline void Magick::Image::lineWidth ( const double lineWidth_ ) { strokeWidth( lineWidth_ ); } inline double Magick::Image::lineWidth ( void ) const { return strokeWidth( ); } // Get image storage class inline Magick::ClassType Magick::Image::classType ( void ) const { return static_cast(constImage()->storage_class); } // Get number of image columns inline unsigned int Magick::Image::columns ( void ) const { return constImage()->columns; } // Get number of image rows inline unsigned int Magick::Image::rows ( void ) const { return constImage()->rows; } #endif // Magick_Image_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Include.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2018 // // Inclusion of GraphicsMagick headers (with namespace magic) #ifndef Magick_Include_header #define Magick_Include_header #if !defined(_MAGICK_CONFIG_H) # define _MAGICK_CONFIG_H # if !defined(vms) && !defined(macintosh) # include "magick/magick_config.h" # else # include "magick_config.h" # endif # undef inline // Remove possible definition from config.h # undef class #endif #include #include #include #include #include /* POSIX 1990 header and declares size_t and ssize_t */ #if defined(__BORLANDC__) # include /* Borland C++ Builder 4.0 requirement */ #endif // defined(__BORLANDC__) // // Include GraphicsMagick headers into namespace "MagickLib". If // MAGICK_IMPLEMENTATION is defined, include GraphicsMagick development // headers. This scheme minimizes the possibility of conflict with // user code. // namespace MagickLib { #include #undef inline // Remove possible definition from config.h #undef class } // // Provide appropriate DLL imports/exports for Visual C++, // Borland C++Builder and MinGW builds. // #if (defined(WIN32) || defined(WIN64)) && !defined (__CYGWIN__) //&& !defined(__MINGW32__) # define MagickCplusPlusDLLSupported #endif #if defined(MagickCplusPlusDLLSupported) # if defined(_MT) && defined(_DLL) && !defined(_LIB) && !defined(STATIC_MAGICK) // // In a native Windows build, the following defines are used: // // _MT = Multithreaded // _DLL = Using code is part of a DLL // _LIB = Using code is being built as a library. // _MAGICKMOD_ = Build uses loadable modules (Magick++ does not care about this) // // In the case where GraphicsMagick is built as a static library but the // using code is dynamic, STATIC_MAGICK may be defined in the project to // override triggering dynamic library behavior. // # if defined(_VISUALC_) # define MagickDLLExplicitTemplate /* Explicit template instantiation in DLLs */ # pragma warning( disable: 4273 ) /* Disable the stupid dll linkage warnings */ # pragma warning( disable: 4251 ) # endif # if !defined(MAGICK_IMPLEMENTATION) # define MagickDLLDecl __declspec(dllimport) # define MagickDLLDeclExtern extern __declspec(dllimport) # if defined(_VISUALC_) # pragma message( "Magick++ lib DLL import" ) # endif # else # if defined(__BORLANDC__) || defined(__MINGW32__) # define MagickDLLDecl __declspec(dllexport) # define MagickDLLDeclExtern __declspec(dllexport) # if defined(__BORLANDC__) # pragma message( "BCBMagick++ lib DLL export" ) # endif # else # define MagickDLLDecl __declspec(dllexport) # define MagickDLLDeclExtern extern __declspec(dllexport) # endif # if defined(_VISUALC_) # pragma message( "Magick++ lib DLL export" ) # endif # endif # else # define MagickDLLDecl # define MagickDLLDeclExtern # if defined(_VISUALC_) # pragma message( "Magick++ lib static interface" ) # endif # if defined(_MSC_VER) && defined(STATIC_MAGICK) && !defined(NOAUTOLINK_MAGICK) # if defined(_DEBUG) # if defined(HasBZLIB) # pragma comment(lib, "CORE_DB_bzlib_.lib") # endif # pragma comment(lib, "CORE_DB_coders_.lib") # pragma comment(lib, "CORE_DB_filters_.lib") # if defined(HasJBIG) # pragma comment(lib, "CORE_DB_jbig_.lib") # endif # if defined(HasJP2) # pragma comment(lib, "CORE_DB_jp2_.lib") # endif # if defined(HasJPEG) # pragma comment(lib, "CORE_DB_jpeg_.lib") # endif # if defined(HasLCMS) # pragma comment(lib, "CORE_DB_lcms_.lib") # endif # if defined(HasXML) # pragma comment(lib, "CORE_DB_libxml_.lib") # endif # pragma comment(lib, "CORE_DB_magick_.lib") # pragma comment(lib, "CORE_DB_Magick++_.lib") # if defined(HasPNG) # pragma comment(lib, "CORE_DB_png_.lib") # endif # if defined(HasTIFF) # pragma comment(lib, "CORE_DB_tiff_.lib") # endif # if defined(HasTTF) # pragma comment(lib, "CORE_DB_ttf_.lib") # endif # pragma comment(lib, "CORE_DB_wand_.lib") # if defined(HasWEBP) # pragma comment(lib, "CORE_DB_webp_.lib") # endif # if defined(HasWMFlite) # pragma comment(lib, "CORE_DB_wmf_.lib") # endif # if defined(HasX11) # pragma comment(lib, "CORE_DB_xlib_.lib") # endif # if defined(HasZLIB) # pragma comment(lib, "CORE_DB_zlib_.lib") # endif # else # if defined(HasBZLIB) # pragma comment(lib, "CORE_RL_bzlib_.lib") # endif # pragma comment(lib, "CORE_RL_coders_.lib") # pragma comment(lib, "CORE_RL_filters_.lib") # if defined(HasJBIG) # pragma comment(lib, "CORE_RL_jbig_.lib") # endif # if defined(HasJP2) # pragma comment(lib, "CORE_RL_jp2_.lib") # endif # if defined(HasJPEG) # pragma comment(lib, "CORE_RL_jpeg_.lib") # endif # if defined(HasLCMS) # pragma comment(lib, "CORE_RL_lcms_.lib") # endif # if defined(HasXML) # pragma comment(lib, "CORE_RL_libxml_.lib") # endif # pragma comment(lib, "CORE_RL_magick_.lib") # pragma comment(lib, "CORE_RL_Magick++_.lib") # if defined(HasPNG) # pragma comment(lib, "CORE_RL_png_.lib") # endif # if defined(HasTIFF) # pragma comment(lib, "CORE_RL_tiff_.lib") # endif # if defined(HasTTF) # pragma comment(lib, "CORE_RL_ttf_.lib") # endif # pragma comment(lib, "CORE_RL_wand_.lib") # if defined(HasWEBP) # pragma comment(lib, "CORE_RL_webp_.lib") # endif # if defined(HasWMFlite) # pragma comment(lib, "CORE_RL_wmf_.lib") # endif # if defined(HasX11) # pragma comment(lib, "CORE_RL_xlib_.lib") # endif # if defined(HasZLIB) # pragma comment(lib, "CORE_RL_zlib_.lib") # endif # endif # if defined(_WIN32_WCE) # pragma comment(lib, "wsock32.lib") # else # pragma comment(lib, "ws2_32.lib") # endif # endif # endif #else # define MagickDLLDecl # define MagickDLLDeclExtern #endif #if (defined(WIN32) || defined(WIN64)) && defined(_VISUALC_) # pragma warning(disable : 4996) /* function deprecation warnings */ #endif #if defined(MAGICK_IMPLEMENTATION) namespace MagickLib { # include "magick/enum_strings.h" } #endif // // Import GraphicsMagick symbols and types which are used as part of the // Magick++ API definition into namespace "Magick". // namespace Magick { // The datatype for an RGB component using MagickLib::Quantum; // Image class types using MagickLib::ClassType; using MagickLib::UndefinedClass; using MagickLib::DirectClass; using MagickLib::PseudoClass; // Channel types using MagickLib::ChannelType; using MagickLib::UndefinedChannel; using MagickLib::RedChannel; using MagickLib::CyanChannel; using MagickLib::GreenChannel; using MagickLib::MagentaChannel; using MagickLib::BlueChannel; using MagickLib::YellowChannel; using MagickLib::OpacityChannel; using MagickLib::BlackChannel; using MagickLib::MatteChannel; using MagickLib::AllChannels; using MagickLib::GrayChannel; // Color-space types using MagickLib::ColorspaceType; using MagickLib::UndefinedColorspace; using MagickLib::RGBColorspace; using MagickLib::GRAYColorspace; using MagickLib::TransparentColorspace; using MagickLib::OHTAColorspace; using MagickLib::XYZColorspace; using MagickLib::YCbCrColorspace; using MagickLib::YCCColorspace; using MagickLib::YIQColorspace; using MagickLib::YPbPrColorspace; using MagickLib::YUVColorspace; using MagickLib::CMYKColorspace; using MagickLib::sRGBColorspace; using MagickLib::HSLColorspace; using MagickLib::HWBColorspace; using MagickLib::LABColorspace; using MagickLib::CineonLogRGBColorspace; using MagickLib::Rec601LumaColorspace; using MagickLib::Rec709LumaColorspace; using MagickLib::Rec709YCbCrColorspace; // Composition operations using MagickLib::AddCompositeOp; using MagickLib::AtopCompositeOp; using MagickLib::BumpmapCompositeOp; using MagickLib::ClearCompositeOp; using MagickLib::ColorizeCompositeOp; using MagickLib::CompositeOperator; using MagickLib::CopyBlueCompositeOp; using MagickLib::CopyCompositeOp; using MagickLib::CopyGreenCompositeOp; using MagickLib::CopyOpacityCompositeOp; using MagickLib::CopyRedCompositeOp; using MagickLib::DarkenCompositeOp; using MagickLib::DifferenceCompositeOp; using MagickLib::DisplaceCompositeOp; using MagickLib::DissolveCompositeOp; using MagickLib::HueCompositeOp; using MagickLib::InCompositeOp; using MagickLib::LightenCompositeOp; using MagickLib::LuminizeCompositeOp; using MagickLib::MinusCompositeOp; using MagickLib::ModulateCompositeOp; using MagickLib::MultiplyCompositeOp; using MagickLib::NoCompositeOp; using MagickLib::OutCompositeOp; using MagickLib::OverCompositeOp; using MagickLib::OverlayCompositeOp; using MagickLib::PlusCompositeOp; using MagickLib::SaturateCompositeOp; using MagickLib::ScreenCompositeOp; using MagickLib::SubtractCompositeOp; using MagickLib::ThresholdCompositeOp; using MagickLib::UndefinedCompositeOp; using MagickLib::XorCompositeOp; using MagickLib::CopyCyanCompositeOp; using MagickLib::CopyMagentaCompositeOp; using MagickLib::CopyYellowCompositeOp; using MagickLib::CopyBlackCompositeOp; using MagickLib::DivideCompositeOp; using MagickLib::HardLightCompositeOp; using MagickLib::ExclusionCompositeOp; using MagickLib::ColorDodgeCompositeOp; using MagickLib::ColorBurnCompositeOp; using MagickLib::SoftLightCompositeOp; using MagickLib::LinearBurnCompositeOp; using MagickLib::LinearDodgeCompositeOp; using MagickLib::LinearLightCompositeOp; using MagickLib::VividLightCompositeOp; using MagickLib::PinLightCompositeOp; using MagickLib::HardMixCompositeOp; // Compression algorithms using MagickLib::CompressionType; using MagickLib::UndefinedCompression; using MagickLib::NoCompression; using MagickLib::BZipCompression; using MagickLib::FaxCompression; using MagickLib::Group3Compression; using MagickLib::Group4Compression; using MagickLib::JPEGCompression; using MagickLib::LZWCompression; using MagickLib::RLECompression; using MagickLib::ZipCompression; using MagickLib::LZMACompression; using MagickLib::JPEG2000Compression; using MagickLib::JBIG1Compression; using MagickLib::JBIG2Compression; using MagickLib::ZSTDCompression; using MagickLib::WebPCompression; using MagickLib::DisposeType; using MagickLib::UndefinedDispose; using MagickLib::NoneDispose; using MagickLib::BackgroundDispose; using MagickLib::PreviousDispose; // Endian options using MagickLib::EndianType; using MagickLib::UndefinedEndian; using MagickLib::LSBEndian; using MagickLib::MSBEndian; using MagickLib::NativeEndian; // Exception types using MagickLib::ExceptionType; using MagickLib::UndefinedException; using MagickLib::EventException; using MagickLib::ExceptionEvent; using MagickLib::ResourceEvent; using MagickLib::ResourceLimitEvent; using MagickLib::TypeEvent; using MagickLib::AnnotateEvent; using MagickLib::OptionEvent; using MagickLib::DelegateEvent; using MagickLib::MissingDelegateEvent; using MagickLib::CorruptImageEvent; using MagickLib::FileOpenEvent; using MagickLib::BlobEvent; using MagickLib::StreamEvent; using MagickLib::CacheEvent; using MagickLib::CoderEvent; using MagickLib::ModuleEvent; using MagickLib::DrawEvent; using MagickLib::RenderEvent; using MagickLib::ImageEvent; using MagickLib::WandEvent; using MagickLib::TemporaryFileEvent; using MagickLib::TransformEvent; using MagickLib::XServerEvent; using MagickLib::X11Event; using MagickLib::UserEvent; using MagickLib::MonitorEvent; using MagickLib::LocaleEvent; using MagickLib::DeprecateEvent; using MagickLib::RegistryEvent; using MagickLib::ConfigureEvent; using MagickLib::WarningException; using MagickLib::ExceptionWarning; using MagickLib::ResourceWarning; using MagickLib::ResourceLimitWarning; using MagickLib::TypeWarning; using MagickLib::AnnotateWarning; using MagickLib::OptionWarning; using MagickLib::DelegateWarning; using MagickLib::MissingDelegateWarning; using MagickLib::CorruptImageWarning; using MagickLib::FileOpenWarning; using MagickLib::BlobWarning; using MagickLib::StreamWarning; using MagickLib::CacheWarning; using MagickLib::CoderWarning; using MagickLib::ModuleWarning; using MagickLib::DrawWarning; using MagickLib::RenderWarning; using MagickLib::ImageWarning; using MagickLib::WandWarning; using MagickLib::TemporaryFileWarning; using MagickLib::TransformWarning; using MagickLib::XServerWarning; using MagickLib::X11Warning; using MagickLib::UserWarning; using MagickLib::MonitorWarning; using MagickLib::LocaleWarning; using MagickLib::DeprecateWarning; using MagickLib::RegistryWarning; using MagickLib::ConfigureWarning; using MagickLib::ErrorException; using MagickLib::ExceptionError; using MagickLib::ResourceError; using MagickLib::ResourceLimitError; using MagickLib::TypeError; using MagickLib::AnnotateError; using MagickLib::OptionError; using MagickLib::DelegateError; using MagickLib::MissingDelegateError; using MagickLib::CorruptImageError; using MagickLib::FileOpenError; using MagickLib::BlobError; using MagickLib::StreamError; using MagickLib::CacheError; using MagickLib::CoderError; using MagickLib::ModuleError; using MagickLib::DrawError; using MagickLib::RenderError; using MagickLib::ImageError; using MagickLib::WandError; using MagickLib::TemporaryFileError; using MagickLib::TransformError; using MagickLib::XServerError; using MagickLib::X11Error; using MagickLib::UserError; using MagickLib::MonitorError; using MagickLib::LocaleError; using MagickLib::DeprecateError; using MagickLib::RegistryError; using MagickLib::ConfigureError; using MagickLib::FatalErrorException; using MagickLib::ExceptionFatalError; using MagickLib::ResourceFatalError; using MagickLib::ResourceLimitFatalError; using MagickLib::TypeFatalError; using MagickLib::AnnotateFatalError; using MagickLib::OptionFatalError; using MagickLib::DelegateFatalError; using MagickLib::MissingDelegateFatalError; using MagickLib::CorruptImageFatalError; using MagickLib::FileOpenFatalError; using MagickLib::BlobFatalError; using MagickLib::StreamFatalError; using MagickLib::CacheFatalError; using MagickLib::CoderFatalError; using MagickLib::ModuleFatalError; using MagickLib::DrawFatalError; using MagickLib::RenderFatalError; using MagickLib::ImageFatalError; using MagickLib::WandFatalError; using MagickLib::TemporaryFileFatalError; using MagickLib::TransformFatalError; using MagickLib::XServerFatalError; using MagickLib::X11FatalError; using MagickLib::UserFatalError; using MagickLib::MonitorFatalError; using MagickLib::LocaleFatalError; using MagickLib::DeprecateFatalError; using MagickLib::RegistryFatalError; using MagickLib::ConfigureFatalError; // Fill rules using MagickLib::FillRule; using MagickLib::UndefinedRule; using MagickLib::EvenOddRule; using MagickLib::NonZeroRule; // Filter types using MagickLib::FilterTypes; using MagickLib::UndefinedFilter; using MagickLib::PointFilter; using MagickLib::BoxFilter; using MagickLib::TriangleFilter; using MagickLib::HermiteFilter; using MagickLib::HanningFilter; using MagickLib::HammingFilter; using MagickLib::BlackmanFilter; using MagickLib::GaussianFilter; using MagickLib::QuadraticFilter; using MagickLib::CubicFilter; using MagickLib::CatromFilter; using MagickLib::MitchellFilter; using MagickLib::LanczosFilter; using MagickLib::BesselFilter; using MagickLib::SincFilter; // Bit gravity using MagickLib::GravityType; using MagickLib::ForgetGravity; using MagickLib::NorthWestGravity; using MagickLib::NorthGravity; using MagickLib::NorthEastGravity; using MagickLib::WestGravity; using MagickLib::CenterGravity; using MagickLib::EastGravity; using MagickLib::SouthWestGravity; using MagickLib::SouthGravity; using MagickLib::SouthEastGravity; using MagickLib::StaticGravity; // Image types using MagickLib::ImageType; using MagickLib::UndefinedType; using MagickLib::BilevelType; using MagickLib::GrayscaleType; using MagickLib::GrayscaleMatteType; using MagickLib::PaletteType; using MagickLib::PaletteMatteType; using MagickLib::TrueColorType; using MagickLib::TrueColorMatteType; using MagickLib::ColorSeparationType; using MagickLib::ColorSeparationMatteType; using MagickLib::OptimizeType; // Interlace types using MagickLib::InterlaceType; using MagickLib::UndefinedInterlace; using MagickLib::NoInterlace; using MagickLib::LineInterlace; using MagickLib::PlaneInterlace; using MagickLib::PartitionInterlace; // Line cap types using MagickLib::LineCap; using MagickLib::UndefinedCap; using MagickLib::ButtCap; using MagickLib::RoundCap; using MagickLib::SquareCap; // Line join types using MagickLib::LineJoin; using MagickLib::UndefinedJoin; using MagickLib::MiterJoin; using MagickLib::RoundJoin; using MagickLib::BevelJoin; // Noise types using MagickLib::NoiseType; using MagickLib::UniformNoise; using MagickLib::GaussianNoise; using MagickLib::MultiplicativeGaussianNoise; using MagickLib::ImpulseNoise; using MagickLib::LaplacianNoise; using MagickLib::PoissonNoise; using MagickLib::RandomNoise; // Orientation types using MagickLib::OrientationType; using MagickLib::UndefinedOrientation; using MagickLib::TopLeftOrientation; using MagickLib::TopRightOrientation; using MagickLib::BottomRightOrientation; using MagickLib::BottomLeftOrientation; using MagickLib::LeftTopOrientation; using MagickLib::RightTopOrientation; using MagickLib::RightBottomOrientation; using MagickLib::LeftBottomOrientation; // Paint methods using MagickLib::PaintMethod; using MagickLib::PointMethod; using MagickLib::ReplaceMethod; using MagickLib::FloodfillMethod; using MagickLib::FillToBorderMethod; using MagickLib::ResetMethod; // Arithmetic and bitwise operators using MagickLib::UndefinedQuantumOp; using MagickLib::AddQuantumOp; using MagickLib::AndQuantumOp; using MagickLib::AssignQuantumOp; using MagickLib::DivideQuantumOp; using MagickLib::LShiftQuantumOp; using MagickLib::MultiplyQuantumOp; using MagickLib::OrQuantumOp; using MagickLib::RShiftQuantumOp; using MagickLib::SubtractQuantumOp; using MagickLib::ThresholdQuantumOp; using MagickLib::ThresholdBlackQuantumOp; using MagickLib::ThresholdWhiteQuantumOp; using MagickLib::ThresholdBlackNegateQuantumOp; using MagickLib::ThresholdWhiteNegateQuantumOp; using MagickLib::XorQuantumOp; using MagickLib::NoiseGaussianQuantumOp; using MagickLib::NoiseImpulseQuantumOp; using MagickLib::NoiseLaplacianQuantumOp; using MagickLib::NoiseMultiplicativeQuantumOp; using MagickLib::NoisePoissonQuantumOp; using MagickLib::NoiseUniformQuantumOp; using MagickLib::NegateQuantumOp; using MagickLib::GammaQuantumOp; using MagickLib::DepthQuantumOp; using MagickLib::LogQuantumOp; using MagickLib::MaxQuantumOp; using MagickLib::MinQuantumOp; using MagickLib::PowQuantumOp; using MagickLib::QuantumOperator; // Preview types. Not currently used by Magick++ using MagickLib::PreviewType; using MagickLib::UndefinedPreview; using MagickLib::RotatePreview; using MagickLib::ShearPreview; using MagickLib::RollPreview; using MagickLib::HuePreview; using MagickLib::SaturationPreview; using MagickLib::BrightnessPreview; using MagickLib::GammaPreview; using MagickLib::SpiffPreview; using MagickLib::DullPreview; using MagickLib::GrayscalePreview; using MagickLib::QuantizePreview; using MagickLib::DespecklePreview; using MagickLib::ReduceNoisePreview; using MagickLib::AddNoisePreview; using MagickLib::SharpenPreview; using MagickLib::BlurPreview; using MagickLib::ThresholdPreview; using MagickLib::EdgeDetectPreview; using MagickLib::SpreadPreview; using MagickLib::SolarizePreview; using MagickLib::ShadePreview; using MagickLib::RaisePreview; using MagickLib::SegmentPreview; using MagickLib::SwirlPreview; using MagickLib::ImplodePreview; using MagickLib::WavePreview; using MagickLib::OilPaintPreview; using MagickLib::CharcoalDrawingPreview; using MagickLib::JPEGPreview; // Quantum types using MagickLib::QuantumType; using MagickLib::IndexQuantum; using MagickLib::GrayQuantum; using MagickLib::IndexAlphaQuantum; using MagickLib::GrayAlphaQuantum; using MagickLib::RedQuantum; using MagickLib::CyanQuantum; using MagickLib::GreenQuantum; using MagickLib::YellowQuantum; using MagickLib::BlueQuantum; using MagickLib::MagentaQuantum; using MagickLib::AlphaQuantum; using MagickLib::BlackQuantum; using MagickLib::RGBQuantum; using MagickLib::RGBAQuantum; using MagickLib::CMYKQuantum; using MagickLib::CIEYQuantum; using MagickLib::CIEXYZQuantum; // Quantum sample types using MagickLib::QuantumSampleType; using MagickLib::UndefinedQuantumSampleType; using MagickLib::UnsignedQuantumSampleType; using MagickLib::FloatQuantumSampleType; // Rendering intents using MagickLib::RenderingIntent; using MagickLib::UndefinedIntent; using MagickLib::SaturationIntent; using MagickLib::PerceptualIntent; using MagickLib::AbsoluteIntent; using MagickLib::RelativeIntent; // Resolution units using MagickLib::ResolutionType; using MagickLib::UndefinedResolution; using MagickLib::PixelsPerInchResolution; using MagickLib::PixelsPerCentimeterResolution; // PixelPacket structure using MagickLib::PixelPacket; // IndexPacket type using MagickLib::IndexPacket; // ImageStatistics type using MagickLib::ImageStatistics; // StorageType type using MagickLib::StorageType; using MagickLib::CharPixel; using MagickLib::ShortPixel; using MagickLib::IntegerPixel; using MagickLib::LongPixel; using MagickLib::FloatPixel; using MagickLib::DoublePixel; // StretchType type using MagickLib::StretchType; using MagickLib::NormalStretch; using MagickLib::UltraCondensedStretch; using MagickLib::ExtraCondensedStretch; using MagickLib::CondensedStretch; using MagickLib::SemiCondensedStretch; using MagickLib::SemiExpandedStretch; using MagickLib::ExpandedStretch; using MagickLib::ExtraExpandedStretch; using MagickLib::UltraExpandedStretch; using MagickLib::AnyStretch; // StyleType type using MagickLib::StyleType; using MagickLib::NormalStyle; using MagickLib::ItalicStyle; using MagickLib::ObliqueStyle; using MagickLib::AnyStyle; // Decoration types using MagickLib::DecorationType; using MagickLib::NoDecoration; using MagickLib::UnderlineDecoration; using MagickLib::OverlineDecoration; using MagickLib::LineThroughDecoration; // Resource types using MagickLib::ResourceType; using MagickLib::DiskResource; using MagickLib::FileResource; using MagickLib::MapResource; using MagickLib::MemoryResource; using MagickLib::PixelsResource; using MagickLib::ThreadsResource; using MagickLib::WidthResource; using MagickLib::HeightResource; // Virtual pixel methods using MagickLib::VirtualPixelMethod; using MagickLib::UndefinedVirtualPixelMethod; using MagickLib::ConstantVirtualPixelMethod; using MagickLib::EdgeVirtualPixelMethod; using MagickLib::MirrorVirtualPixelMethod; using MagickLib::TileVirtualPixelMethod; #if defined(MAGICK_IMPLEMENTATION) // // GraphicsMagick symbols used in implementation code // using MagickLib::AccessDefinition; using MagickLib::AccessImmutableIndexes; using MagickLib::AccessMutableIndexes; using MagickLib::AcquireCacheViewPixels; using MagickLib::AcquireImagePixels; using MagickLib::AdaptiveThresholdImage; using MagickLib::AddDefinition; using MagickLib::AddDefinitions; using MagickLib::AddNoiseImage; using MagickLib::AddNoiseImageChannel; using MagickLib::AffineMatrix; using MagickLib::AffineTransformImage; using MagickLib::AllocateImage; using MagickLib::AnnotateImage; using MagickLib::AreaValue; using MagickLib::AspectValue; using MagickLib::Base64Decode; using MagickLib::Base64Encode; using MagickLib::BlobError; using MagickLib::BlobFatalError; using MagickLib::BlobToImage; using MagickLib::BlobWarning; using MagickLib::BlurImage; using MagickLib::BlurImageChannel; using MagickLib::BorderImage; using MagickLib::CacheError; using MagickLib::CacheFatalError; using MagickLib::CacheWarning; using MagickLib::CdlImage; using MagickLib::ChannelImage; using MagickLib::CharcoalImage; using MagickLib::ChopImage; using MagickLib::CloneDrawInfo; using MagickLib::CloneImage; using MagickLib::CloneImageInfo; using MagickLib::CloneQuantizeInfo; using MagickLib::CloseCacheView; using MagickLib::CoderError; using MagickLib::CoderFatalError; using MagickLib::CoderWarning; using MagickLib::ColorFloodfillImage; using MagickLib::ColorizeImage; using MagickLib::ColorMatrixImage; using MagickLib::CompositeImage; using MagickLib::ConfigureError; using MagickLib::ConfigureFatalError; using MagickLib::ConfigureWarning; using MagickLib::ConstituteImage; using MagickLib::ContrastImage; using MagickLib::ConvolveImage; using MagickLib::CopyException; using MagickLib::CorruptImageError; using MagickLib::CorruptImageFatalError; using MagickLib::CorruptImageWarning; using MagickLib::CropImage; using MagickLib::CycleColormapImage; using MagickLib::DelegateError; using MagickLib::DelegateFatalError; using MagickLib::DelegateWarning; using MagickLib::DeleteMagickRegistry; using MagickLib::DespeckleImage; using MagickLib::DestroyDrawInfo; using MagickLib::DestroyExceptionInfo; using MagickLib::DestroyImageInfo; using MagickLib::DestroyImageList; using MagickLib::DestroyMagick; using MagickLib::DestroyQuantizeInfo; using MagickLib::DispatchImage; using MagickLib::DisplayImages; using MagickLib::DrawAffine; using MagickLib::DrawAllocateContext; using MagickLib::DrawAnnotation; using MagickLib::DrawArc; using MagickLib::DrawBezier; using MagickLib::DrawCircle; using MagickLib::DrawColor; using MagickLib::DrawComment; using MagickLib::DrawComposite; using MagickLib::DrawContext; using MagickLib::DrawDestroyContext; using MagickLib::DrawEllipse; using MagickLib::DrawError; using MagickLib::DrawFatalError; using MagickLib::DrawImage; using MagickLib::DrawInfo; using MagickLib::DrawLine; using MagickLib::DrawMatte; using MagickLib::DrawPathClose; using MagickLib::DrawPathCurveToAbsolute; using MagickLib::DrawPathCurveToQuadraticBezierAbsolute; using MagickLib::DrawPathCurveToQuadraticBezierRelative; using MagickLib::DrawPathCurveToQuadraticBezierSmoothAbsolute; using MagickLib::DrawPathCurveToQuadraticBezierSmoothRelative; using MagickLib::DrawPathCurveToRelative; using MagickLib::DrawPathCurveToSmoothAbsolute; using MagickLib::DrawPathCurveToSmoothRelative; using MagickLib::DrawPathEllipticArcAbsolute; using MagickLib::DrawPathEllipticArcRelative; using MagickLib::DrawPathFinish; using MagickLib::DrawPathLineToAbsolute; using MagickLib::DrawPathLineToHorizontalAbsolute; using MagickLib::DrawPathLineToHorizontalRelative; using MagickLib::DrawPathLineToRelative; using MagickLib::DrawPathLineToVerticalAbsolute; using MagickLib::DrawPathLineToVerticalRelative; using MagickLib::DrawPathMoveToAbsolute; using MagickLib::DrawPathMoveToRelative; using MagickLib::DrawPathStart; using MagickLib::DrawPoint; using MagickLib::DrawPolygon; using MagickLib::DrawPolyline; using MagickLib::DrawPopClipPath; using MagickLib::DrawPopDefs; using MagickLib::DrawPopGraphicContext; using MagickLib::DrawPopPattern; using MagickLib::DrawPushClipPath; using MagickLib::DrawPushDefs; using MagickLib::DrawPushGraphicContext; using MagickLib::DrawPushPattern; using MagickLib::DrawRectangle; using MagickLib::DrawRender; using MagickLib::DrawRotate; using MagickLib::DrawRoundRectangle; using MagickLib::DrawScale; using MagickLib::DrawSetClipPath; using MagickLib::DrawSetClipRule; using MagickLib::DrawSetClipUnits; using MagickLib::DrawSetFillColor; using MagickLib::DrawSetFillColorString; using MagickLib::DrawSetFillOpacity; using MagickLib::DrawSetFillPatternURL; using MagickLib::DrawSetFillRule; using MagickLib::DrawSetFont; using MagickLib::DrawSetFontFamily; using MagickLib::DrawSetFontSize; using MagickLib::DrawSetFontStretch; using MagickLib::DrawSetFontStyle; using MagickLib::DrawSetFontWeight; using MagickLib::DrawSetGravity; using MagickLib::DrawSetStrokeAntialias; using MagickLib::DrawSetStrokeColor; using MagickLib::DrawSetStrokeColorString; using MagickLib::DrawSetStrokeDashArray; using MagickLib::DrawSetStrokeDashOffset; using MagickLib::DrawSetStrokeLineCap; using MagickLib::DrawSetStrokeLineJoin; using MagickLib::DrawSetStrokeMiterLimit; using MagickLib::DrawSetStrokeOpacity; using MagickLib::DrawSetStrokePatternURL; using MagickLib::DrawSetStrokeWidth; using MagickLib::DrawSetTextAntialias; using MagickLib::DrawSetTextDecoration; using MagickLib::DrawSetTextEncoding; using MagickLib::DrawSetTextUnderColor; using MagickLib::DrawSetTextUnderColorString; using MagickLib::DrawSetViewbox; using MagickLib::DrawSkewX; using MagickLib::DrawSkewY; using MagickLib::DrawTranslate; using MagickLib::DrawWarning; using MagickLib::EdgeImage; using MagickLib::EmbossImage; using MagickLib::EnhanceImage; using MagickLib::EqualizeImage; using MagickLib::ExceptionInfo; using MagickLib::ExecuteModuleProcess; using MagickLib::ExportImagePixelArea; using MagickLib::ExtentImage; using MagickLib::FileOpenError; using MagickLib::FileOpenFatalError; using MagickLib::FileOpenWarning; using MagickLib::FlattenImages; using MagickLib::FlipImage; using MagickLib::FlopImage; using MagickLib::FormatString; using MagickLib::FrameImage; using MagickLib::FrameInfo; using MagickLib::GammaImage; using MagickLib::GammaImage; using MagickLib::GaussianBlurImage; using MagickLib::GaussianBlurImageChannel; using MagickLib::GetBlobSize; using MagickLib::GetCacheViewIndexes; using MagickLib::GetCacheViewPixels; using MagickLib::GetColorTuple; using MagickLib::GetDrawInfo; using MagickLib::GetExceptionInfo; using MagickLib::GetGeometry; using MagickLib::GetImageAttribute; using MagickLib::GetImageBoundingBox; using MagickLib::GetImageChannelDepth; using MagickLib::GetImageClipMask; using MagickLib::GetImageDepth; using MagickLib::GetImageGeometry; using MagickLib::GetImageInfo; using MagickLib::GetImagePixels; using MagickLib::GetImageProfile; using MagickLib::GetImageQuantizeError; using MagickLib::GetImageStatistics; using MagickLib::GetImageType; using MagickLib::GetMagickGeometry; using MagickLib::GetMagickInfo; using MagickLib::GetMagickInfoArray; using MagickLib::GetMagickRegistry; using MagickLib::GetNumberColors; using MagickLib::GetPageGeometry; using MagickLib::GetQuantizeInfo; using MagickLib::GetTypeMetrics; using MagickLib::GlobExpression; using MagickLib::GreaterValue; using MagickLib::HaldClutImage; using MagickLib::HSLTransform; using MagickLib::HeightValue; using MagickLib::IdentityAffine; using MagickLib::ImageAttribute; using MagickLib::ImageError; using MagickLib::ImageFatalError; using MagickLib::ImageInfo; using MagickLib::ImageInfoRegistryType; using MagickLib::ImageRegistryType; using MagickLib::ImageToBlob; using MagickLib::ImageWarning; using MagickLib::ImplodeImage; using MagickLib::ImportImagePixelArea; using MagickLib::IsEventLogging; using MagickLib::IsGeometry; using MagickLib::IsImagesEqual; using MagickLib::IsSubimage; using MagickLib::LessValue; using MagickLib::LevelImage; using MagickLib::LevelImageChannel; using MagickLib::LocaleCompare; using MagickLib::LogMagickEvent; using MagickLib::MagickFree; using MagickLib::MagickInfo; using MagickLib::MagickMalloc; using MagickLib::MagickRealloc; using MagickLib::MagickStrlCpy; using MagickLib::MagickToMime; using MagickLib::MagnifyImage; using MagickLib::MapImage; using MagickLib::MatteFloodfillImage; using MagickLib::MedianFilterImage; using MagickLib::MinifyImage; using MagickLib::MinimumValue; using MagickLib::MissingDelegateError; using MagickLib::MissingDelegateFatalError; using MagickLib::MissingDelegateWarning; using MagickLib::ModulateImage; using MagickLib::ModuleError; using MagickLib::ModuleFatalError; using MagickLib::ModuleWarning; using MagickLib::MonitorError; using MagickLib::MonitorFatalError; using MagickLib::MonitorWarning; using MagickLib::MontageInfo; using MagickLib::MotionBlurImage; using MagickLib::NegateImage; using MagickLib::NoValue; using MagickLib::NoiseType; using MagickLib::NormalizeImage; using MagickLib::OilPaintImage; using MagickLib::OpaqueImage; using MagickLib::OpenCacheView; using MagickLib::OptionError; using MagickLib::OptionFatalError; using MagickLib::OptionWarning; using MagickLib::PercentValue; using MagickLib::PingBlob; using MagickLib::PingImage; using MagickLib::PointInfo; using MagickLib::PopImagePixels; using MagickLib::ProfileImage; using MagickLib::ProfileInfo; using MagickLib::PushImagePixels; using MagickLib::QuantizeImage; using MagickLib::QuantizeInfo; using MagickLib::QuantumOperatorImage; using MagickLib::QuantumOperatorRegionImage; using MagickLib::QueryColorDatabase; using MagickLib::RGBTransformImage; using MagickLib::RaiseImage; using MagickLib::RandomChannelThresholdImage; using MagickLib::ReadImage; using MagickLib::RectangleInfo; using MagickLib::RectangleInfo; using MagickLib::ReduceNoiseImage; using MagickLib::RegisterMagickInfo; using MagickLib::RegistryError; using MagickLib::RegistryFatalError; using MagickLib::RegistryType; using MagickLib::RegistryWarning; using MagickLib::RemoveDefinitions; using MagickLib::ResizeImage; using MagickLib::ResourceLimitError; using MagickLib::ResourceLimitFatalError; using MagickLib::ResourceLimitWarning; using MagickLib::RollImage; using MagickLib::RotateImage; using MagickLib::SampleImage; using MagickLib::ScaleImage; using MagickLib::SegmentImage; using MagickLib::SetCacheViewPixels; using MagickLib::SetClientName; using MagickLib::SetImage; using MagickLib::SetImageAttribute; using MagickLib::SetImageChannelDepth; using MagickLib::SetImageClipMask; using MagickLib::SetImageDepth; using MagickLib::SetImageInfo; using MagickLib::SetImageOpacity; using MagickLib::SetImagePixels; using MagickLib::SetImageProfile; using MagickLib::SetImageType; using MagickLib::SetLogEventMask; using MagickLib::SetMagickInfo; using MagickLib::SetMagickRegistry; using MagickLib::SetMagickResourceLimit; using MagickLib::SetMagickResourceLimit; using MagickLib::ShadeImage; using MagickLib::SharpenImage; using MagickLib::SharpenImageChannel; using MagickLib::ShaveImage; using MagickLib::ShearImage; using MagickLib::SignatureImage; using MagickLib::SolarizeImage; using MagickLib::SpreadImage; using MagickLib::SteganoImage; using MagickLib::StereoImage; using MagickLib::StreamError; using MagickLib::StreamFatalError; using MagickLib::StreamWarning; using MagickLib::SwirlImage; using MagickLib::SyncCacheViewPixels; using MagickLib::SyncImage; using MagickLib::SyncImagePixels; using MagickLib::TextureImage; using MagickLib::ThresholdImage; using MagickLib::ThrowException; using MagickLib::ThrowLoggedException; using MagickLib::ThumbnailImage; using MagickLib::TransformHSL; using MagickLib::TransformImage; using MagickLib::TransformRGBImage; using MagickLib::TransparentImage; using MagickLib::TypeError; using MagickLib::TypeFatalError; using MagickLib::TypeWarning; using MagickLib::UndefinedException; using MagickLib::UndefinedRegistryType; using MagickLib::UnregisterMagickInfo; using MagickLib::UnsharpMaskImage; using MagickLib::UnsharpMaskImageChannel; using MagickLib::ViewInfo; using MagickLib::WaveImage; using MagickLib::WidthValue; using MagickLib::WriteImage; using MagickLib::XNegative; using MagickLib::XServerError; using MagickLib::XServerFatalError; using MagickLib::XServerWarning; using MagickLib::XValue; using MagickLib::YNegative; using MagickLib::YValue; using MagickLib::ZoomImage; #endif // MAGICK_IMPLEMENTATION } #endif // Magick_Include_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Montage.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // // Definition of Montage class used to specify montage options. // #if !defined(Magick_Montage_header) #define Magick_Montage_header #include "Magick++/Include.h" #include #include "Magick++/Color.h" #include "Magick++/Geometry.h" // // Basic (Un-framed) Montage // namespace Magick { class MagickDLLDecl Montage { public: Montage( void ); virtual ~Montage( void ); // Specifies the background color that thumbnails are imaged upon. void backgroundColor ( const Color &backgroundColor_ ); Color backgroundColor ( void ) const; // Specifies the image composition algorithm for thumbnails. This // controls the algorithm by which the thumbnail image is placed // on the background. Use of OverCompositeOp is recommended for // use with images that have transparency. This option may have // negative side-effects for images without transparency. void compose ( CompositeOperator compose_ ); CompositeOperator compose ( void ) const; // Specifies the image filename to be used for the generated // montage images. To handle the case were multiple montage images // are generated, a printf-style format may be embedded within the // filename. For example, a filename specification of // image%02d.miff names the montage images as image00.miff, // image01.miff, etc. void fileName( const std::string &fileName_ ); std::string fileName( void ) const; // Specifies the fill color to use for the label text. void fillColor ( const Color &fill_ ); Color fillColor ( void ) const; // Specifies the thumbnail label font. void font ( const std::string &font_ ); std::string font ( void ) const; // Specifies the size of the generated thumbnail. void geometry ( const Geometry &geometry_ ); Geometry geometry ( void ) const; // Specifies the thumbnail positioning within the specified // geometry area. If the thumbnail is smaller in any dimension // than the geometry, then it is placed according to this // specification void gravity ( GravityType gravity_ ); GravityType gravity ( void ) const; // Specifies the format used for the image label. Special format // characters may be embedded in the format string to include // information about the image. void label( const std::string &label_ ); std::string label( void ) const; // Specifies the pen color to use for the label text (same as fill). void penColor ( const Color &pen_ ); Color penColor ( void ) const; // Specifies the thumbnail label font size. void pointSize ( unsigned int pointSize_ ); unsigned int pointSize ( void ) const; // Enable/disable drop-shadow on thumbnails. void shadow ( bool shadow_ ); bool shadow ( void ) const; // Specifies the stroke color to use for the label text . void strokeColor ( const Color &stroke_ ); Color strokeColor ( void ) const; // Specifies a texture image to use as montage background. The // built-in textures "granite:" and "plasma:" are available. A // texture is the same as a background image. void texture ( const std::string &texture_ ); std::string texture ( void ) const; // Specifies the maximum number of montage columns and rows in the // montage. The montage is built by filling out all cells in a row // before advancing to the next row. Once the montage has reached // the maximum number of columns and rows, a new montage image is // started. void tile ( const Geometry &tile_ ); Geometry tile ( void ) const; // Specifies the montage title void title ( const std::string &title_ ); std::string title ( void ) const; // Specifies a montage color to set transparent. This option can // be set the same as the background color in order for the // thumbnails to appear without a background when rendered on an // HTML page. For best effect, ensure that the transparent color // selected does not occur in the rendered thumbnail colors. void transparentColor ( const Color &transparentColor_ ); Color transparentColor ( void ) const; // // Implementation methods/members // // Update elements in existing MontageInfo structure virtual void updateMontageInfo ( MagickLib::MontageInfo &montageInfo_ ) const; protected: private: Color _backgroundColor; // Color that thumbnails are composed on CompositeOperator _compose; // Composition algorithm to use (e.g. ReplaceCompositeOp) std::string _fileName; // Filename to save montages to Color _fill; // Fill color std::string _font; // Label font Geometry _geometry; // Thumbnail width & height plus border width & height GravityType _gravity; // Thumbnail position (e.g. SouthWestGravity) std::string _label; // Thumbnail label (applied to image prior to montage) unsigned int _pointSize; // Font point size bool _shadow; // Enable drop-shadows on thumbnails Color _stroke; // Outline color std::string _texture; // Background texture image Geometry _tile; // Thumbnail rows and colmns std::string _title; // Montage title Color _transparentColor; // Transparent color }; // // Montage With Frames (Extends Basic Montage) // class MagickDLLDecl MontageFramed : public Montage { public: MontageFramed ( void ); /* virtual */ ~MontageFramed ( void ); // Specifies the background color within the thumbnail frame. void borderColor ( const Color &borderColor_ ); Color borderColor ( void ) const; // Specifies the border (in pixels) to place between a thumbnail // and its surrounding frame. This option only takes effect if // thumbnail frames are enabled (via frameGeometry) and the // thumbnail geometry specification doesn't also specify the // thumbnail border width. void borderWidth ( unsigned int borderWidth_ ); unsigned int borderWidth ( void ) const; // Specifies the geometry specification for frame to place around // thumbnail. If this parameter is not specified, then the montage // is unframed. void frameGeometry ( const Geometry &frame_ ); Geometry frameGeometry ( void ) const; // Specifies the thumbnail frame color. void matteColor ( const Color &matteColor_ ); Color matteColor ( void ) const; // // Implementation methods/members // // Update elements in existing MontageInfo structure /* virtual */ void updateMontageInfo ( MagickLib::MontageInfo &montageInfo_ ) const; protected: private: Color _borderColor; // Frame border color unsigned int _borderWidth; // Pixels between thumbnail and surrounding frame Geometry _frame; // Frame geometry (width & height frame thickness) Color _matteColor; // Frame foreground color }; } // namespace Magick // // Inlines // // // Implementation of Montage // inline void Magick::Montage::backgroundColor ( const Magick::Color &backgroundColor_ ) { _backgroundColor = backgroundColor_; } inline Magick::Color Magick::Montage::backgroundColor ( void ) const { return _backgroundColor; } inline void Magick::Montage::compose ( Magick::CompositeOperator compose_ ) { _compose = compose_; } inline Magick::CompositeOperator Magick::Montage::compose ( void ) const { return _compose; } inline void Magick::Montage::fileName( const std::string &fileName_ ) { _fileName = fileName_; } inline std::string Magick::Montage::fileName( void ) const { return _fileName; } inline void Magick::Montage::fillColor ( const Color &fill_ ) { _fill=fill_; } inline Magick::Color Magick::Montage::fillColor ( void ) const { return _fill; } inline void Magick::Montage::font ( const std::string &font_ ) { _font = font_; } inline std::string Magick::Montage::font ( void ) const { return _font; } inline void Magick::Montage::geometry ( const Magick::Geometry &geometry_ ) { _geometry = geometry_; } inline Magick::Geometry Magick::Montage::geometry ( void ) const { return _geometry; } inline void Magick::Montage::gravity ( Magick::GravityType gravity_ ) { _gravity = gravity_; } inline Magick::GravityType Magick::Montage::gravity ( void ) const { return _gravity; } // Apply as attribute to all images before doing montage inline void Magick::Montage::label( const std::string &label_ ) { _label = label_; } inline std::string Magick::Montage::label( void ) const { return _label; } inline void Magick::Montage::penColor ( const Color &pen_ ) { _fill=pen_; _stroke=Color("none"); } inline Magick::Color Magick::Montage::penColor ( void ) const { return _fill; } inline void Magick::Montage::pointSize ( unsigned int pointSize_ ) { _pointSize = pointSize_; } inline unsigned int Magick::Montage::pointSize ( void ) const { return _pointSize; } inline void Magick::Montage::shadow ( bool shadow_ ) { _shadow = shadow_; } inline bool Magick::Montage::shadow ( void ) const { return _shadow; } inline void Magick::Montage::strokeColor ( const Color &stroke_ ) { _stroke=stroke_; } inline Magick::Color Magick::Montage::strokeColor ( void ) const { return _stroke; } inline void Magick::Montage::texture ( const std::string &texture_ ) { _texture = texture_; } inline std::string Magick::Montage::texture ( void ) const { return _texture; } inline void Magick::Montage::tile ( const Geometry &tile_ ) { _tile = tile_; } inline Magick::Geometry Magick::Montage::tile ( void ) const { return _tile; } inline void Magick::Montage::title ( const std::string &title_ ) { _title = title_; } inline std::string Magick::Montage::title ( void ) const { return _title; } // Applied after the fact to montage with TransparentImage() inline void Magick::Montage::transparentColor ( const Magick::Color &transparentColor_ ) { _transparentColor = transparentColor_; } inline Magick::Color Magick::Montage::transparentColor ( void ) const { return _transparentColor; } // // Implementation of MontageFramed // inline void Magick::MontageFramed::borderColor ( const Magick::Color &borderColor_ ) { _borderColor = borderColor_; } inline Magick::Color Magick::MontageFramed::borderColor ( void ) const { return _borderColor; } inline void Magick::MontageFramed::borderWidth ( unsigned int borderWidth_ ) { _borderWidth = borderWidth_; } inline unsigned int Magick::MontageFramed::borderWidth ( void ) const { return _borderWidth; } inline void Magick::MontageFramed::frameGeometry ( const Magick::Geometry &frame_ ) { _frame = frame_; } inline Magick::Geometry Magick::MontageFramed::frameGeometry ( void ) const { return _frame; } inline void Magick::MontageFramed::matteColor ( const Magick::Color &matteColor_ ) { _matteColor = matteColor_; } inline Magick::Color Magick::MontageFramed::matteColor ( void ) const { return _matteColor; } #endif // Magick_Montage_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/Pixels.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002 // // Representation of a pixel view. // #if !defined(Magick_Pixels_header) #define Magick_Pixels_header #include "Magick++/Include.h" #include "Magick++/Color.h" #include "Magick++/Image.h" namespace Magick { class MagickDLLDecl Pixels { public: // Construct pixel view using specified image. Pixels( Magick::Image &image_ ); // Destroy pixel view ~Pixels( void ); // Transfer pixels from the image to the pixel view as defined by // the specified region. Modified pixels may be subsequently // transferred back to the image via sync. PixelPacket* get ( const int x_, const int y_, const unsigned int columns_,const unsigned int rows_ ); // Transfer read-only pixels from the image to the pixel view as // defined by the specified region. const PixelPacket* getConst ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ); // Transfers the image view pixels to the image. void sync ( void ); // Allocate a pixel view region to store image pixels as defined // by the region rectangle. This area is subsequently transferred // from the pixel view to the image via sync. PixelPacket* set ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ); // Return pixel colormap index array IndexPacket* indexes ( void ); // Left ordinate of view int x ( void ) const; // Top ordinate of view int y ( void ) const; // Width of view unsigned int columns ( void ) const; // Height of view unsigned int rows ( void ) const; #if 0 // Transfer one or more pixel components from a buffer or file // into the image pixel view of an image. Used to support image // decoders. void decode ( const QuantumType quantum_, const unsigned char *source_ ) { MagickLib::ReadPixelCache( _image.image(), quantum_, source_ ); } // Transfer one or more pixel components from the image pixel // view to a buffer or file. Used to support image encoders. void encode ( const QuantumType quantum_, const unsigned char *destination_ ) { MagickLib::WritePixelCache( _image.image(), quantum_, destination_ ); } #endif private: // Copying and assigning Pixels is not supported. Pixels( const Pixels& pixels_ ); const Pixels& operator=( const Pixels& pixels_ ); Magick::Image _image; // Image reference MagickLib::ViewInfo* _view; // Image view handle int _x; // Left ordinate of view int _y; // Top ordinate of view unsigned int _columns; // Width of view unsigned int _rows; // Height of view MagickLib:: ExceptionInfo _exception; // Any thrown exception }; // class Pixels } // Magick namespace // // Inline methods // // Left ordinate of view inline int Magick::Pixels::x ( void ) const { return _x; } // Top ordinate of view inline int Magick::Pixels::y ( void ) const { return _y; } // Width of view inline unsigned int Magick::Pixels::columns ( void ) const { return _columns; } // Height of view inline unsigned int Magick::Pixels::rows ( void ) const { return _rows; } #endif // Magick_Pixels_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/STL.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999 - 2018 // // Definition and implementation of template functions for using // Magick::Image with STL containers. // #ifndef Magick_STL_header #define Magick_STL_header #include "Magick++/Include.h" #include #include #include #include #include #include "Magick++/CoderInfo.h" #include "Magick++/Drawable.h" #include "Magick++/Exception.h" #include "Magick++/Montage.h" namespace Magick { // // STL function object declarations/definitions // // Function objects provide the means to invoke an operation on one // or more image objects in an STL-compatable container. The // arguments to the function object constructor(s) are compatible // with the arguments to the equivalent Image class method and // provide the means to supply these options when the function // object is invoked. // For example, to read a GIF animation, set the color red to // transparent for all frames, and write back out: // // list images; // readImages( &images, "animation.gif" ); // for_each( images.begin(), images.end(), transparentImage( "red" ) ); // writeImages( images.begin(), images.end(), "animation.gif" ); // Local adaptive threshold image // http://www.dai.ed.ac.uk/HIPR2/adpthrsh.htm // Width x height define the size of the pixel neighborhood // offset = constant to subtract from pixel neighborhood mean class MagickDLLDecl adaptiveThresholdImage : public std::unary_function { public: adaptiveThresholdImage( const unsigned int width_, const unsigned int height_, const double offset_ = 0.0 ); void operator()( Image &image_ ) const; private: unsigned int _width; unsigned int _height; double _offset; }; // Add noise to image with specified noise type class MagickDLLDecl addNoiseImage : public std::unary_function { public: addNoiseImage ( NoiseType noiseType_ ); void operator()( Image &image_ ) const; private: NoiseType _noiseType; }; // Transform image by specified affine (or free transform) matrix. class MagickDLLDecl affineTransformImage : public std::unary_function { public: affineTransformImage( const DrawableAffine &affine_ ); void operator()( Image &image_ ) const; private: DrawableAffine _affine; }; // Annotate image (draw text on image) class MagickDLLDecl annotateImage : public std::unary_function { public: // Annotate using specified text, and placement location annotateImage ( const std::string &text_, const Geometry &geometry_ ); // Annotate using specified text, bounding area, and placement // gravity annotateImage ( const std::string &text_, const Geometry &geometry_, const GravityType gravity_ ); // Annotate with text using specified text, bounding area, // placement gravity, and rotation. annotateImage ( const std::string &text_, const Geometry &geometry_, const GravityType gravity_, const double degrees_ ); // Annotate with text (bounding area is entire image) and // placement gravity. annotateImage ( const std::string &text_, const GravityType gravity_ ); void operator()( Image &image_ ) const; private: // Copy constructor and assignment are not supported annotateImage(const annotateImage&); annotateImage& operator=(const annotateImage&); const std::string _text; const Geometry _geometry; const GravityType _gravity; const double _degrees; }; // Blur image with specified blur factor class MagickDLLDecl blurImage : public std::unary_function { public: blurImage( const double radius_ = 1, const double sigma_ = 0.5 ); void operator()( Image &image_ ) const; private: double _radius; double _sigma; }; // Border image (add border to image) class MagickDLLDecl borderImage : public std::unary_function { public: borderImage( const Geometry &geometry_ = borderGeometryDefault ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Extract channel from image class MagickDLLDecl channelImage : public std::unary_function { public: channelImage( const ChannelType channel_ ); void operator()( Image &image_ ) const; private: ChannelType _channel; }; // Charcoal effect image (looks like charcoal sketch) class MagickDLLDecl charcoalImage : public std::unary_function { public: charcoalImage( const double radius_ = 1, const double sigma_ = 0.5 ); void operator()( Image &image_ ) const; private: double _radius; double _sigma; }; // Chop image (remove vertical or horizontal subregion of image) class MagickDLLDecl chopImage : public std::unary_function { public: chopImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Colorize image using pen color at specified percent opacity class MagickDLLDecl colorizeImage : public std::unary_function { public: colorizeImage( const unsigned int opacityRed_, const unsigned int opacityGreen_, const unsigned int opacityBlue_, const Color &penColor_ ); colorizeImage( const unsigned int opacity_, const Color &penColor_ ); void operator()( Image &image_ ) const; private: unsigned int _opacityRed; unsigned int _opacityGreen; unsigned int _opacityBlue; Color _penColor; }; // Bake in the ASC-CDL, which is a convention for the for the // exchange of basic primary color grading information between for // the exchange of basic primary color grading information between // equipment and software from different manufacturers. It is a // useful transform for other purposes as well. class MagickDLLDecl cdlImage : public std::unary_function { public: cdlImage( const std::string &cdl_ ); void operator()( Image &image_ ) const; private: std::string _cdl; }; // Apply a color matrix to the image channels. The user supplied // matrix may be of order 1 to 5 (1x1 through 5x5). class MagickDLLDecl colorMatrixImage : public std::unary_function { public: colorMatrixImage( const unsigned int order_, const double *color_matrix_ ); void operator()( Image &image_ ) const; private: unsigned int _order; const double *_color_matrix; }; // Convert the image colorspace representation class MagickDLLDecl colorSpaceImage : public std::unary_function { public: colorSpaceImage( ColorspaceType colorSpace_ ); void operator()( Image &image_ ) const; private: ColorspaceType _colorSpace; }; // Comment image (add comment string to image) class MagickDLLDecl commentImage : public std::unary_function { public: commentImage( const std::string &comment_ ); void operator()( Image &image_ ) const; private: std::string _comment; }; // Compose an image onto another at specified offset and using // specified algorithm class MagickDLLDecl compositeImage : public std::unary_function { public: compositeImage( const Image &compositeImage_, int xOffset_, int yOffset_, CompositeOperator compose_ = InCompositeOp ); compositeImage( const Image &compositeImage_, const Geometry &offset_, CompositeOperator compose_ = InCompositeOp ); void operator()( Image &image_ ) const; private: Image _compositeImage; int _xOffset; int _yOffset; CompositeOperator _compose; }; // Contrast image (enhance intensity differences in image) class MagickDLLDecl contrastImage : public std::unary_function { public: contrastImage( const unsigned int sharpen_ ); void operator()( Image &image_ ) const; private: unsigned int _sharpen; }; // Crop image (subregion of original image) class MagickDLLDecl cropImage : public std::unary_function { public: cropImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Cycle image colormap class MagickDLLDecl cycleColormapImage : public std::unary_function { public: cycleColormapImage( const int amount_ ); void operator()( Image &image_ ) const; private: int _amount; }; // Despeckle image (reduce speckle noise) class MagickDLLDecl despeckleImage : public std::unary_function { public: despeckleImage( void ); void operator()( Image &image_ ) const; private: }; // Draw on image class MagickDLLDecl drawImage : public std::unary_function { public: // Draw on image using a single drawable // Store in list to make implementation easier drawImage( const Drawable &drawable_ ); // Draw on image using a drawable list drawImage( const DrawableList &drawable_ ); void operator()( Image &image_ ) const; private: DrawableList _drawableList; }; // Edge image (hilight edges in image) class MagickDLLDecl edgeImage : public std::unary_function { public: edgeImage( const double radius_ = 0.0 ); void operator()( Image &image_ ) const; private: double _radius; }; // Emboss image (hilight edges with 3D effect) class MagickDLLDecl embossImage : public std::unary_function { public: embossImage( void ); embossImage( const double radius_, const double sigma_ ); void operator()( Image &image_ ) const; private: double _radius; double _sigma; }; // Enhance image (minimize noise) class MagickDLLDecl enhanceImage : public std::unary_function { public: enhanceImage( void ); void operator()( Image &image_ ) const; private: }; // Equalize image (histogram equalization) class MagickDLLDecl equalizeImage : public std::unary_function { public: equalizeImage( void ); void operator()( Image &image_ ) const; private: }; // Create an image canvas using background color sized according to // geometry and composite existing image on it, with image placement // controlled by gravity. Parameters are obtained from existing // image properties if they are not specified via a method // parameter. Parameters which are supported by image properties // (gravity and backgroundColor) update those image properties as a // side-effect. class MagickDLLDecl extentImage : public std::unary_function { public: // Extent image using a geometry extentImage ( const Geometry &geometry_ ); // Extent image using a geometry & gravity extentImage ( const Geometry &geometry_, const GravityType &gravity_ ); // Extent image using a geometry & background color extentImage ( const Geometry &geometry_, const Color &backgroundColor_ ); // Extent image using a geometry, background color & gravity extentImage ( const Geometry &geometry_, const Color &backgroundColor_, const GravityType &gravity_ ); void operator()( Image &image_ ) const; private: // Copy constructor and assignment are not supported extentImage(const extentImage&); extentImage& operator=(const extentImage&); const Geometry _geometry; const Color _backgroundColor; const GravityType _gravity; }; // Color to use when filling drawn objects class MagickDLLDecl fillColorImage : public std::unary_function { public: fillColorImage( const Color &fillColor_ ); void operator()( Image &image_ ) const; private: Color _fillColor; }; // Flip image (reflect each scanline in the vertical direction) class MagickDLLDecl flipImage : public std::unary_function { public: flipImage( void ); void operator()( Image &image_ ) const; private: }; // Flood-fill image with color class MagickDLLDecl floodFillColorImage : public std::unary_function { public: // Flood-fill color across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. floodFillColorImage( const unsigned int x_, const unsigned int y_, const Color &fillColor_ ); floodFillColorImage( const Geometry &point_, const Color &fillColor_ ); // Flood-fill color across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. floodFillColorImage( const unsigned int x_, const unsigned int y_, const Color &fillColor_, const Color &borderColor_ ); floodFillColorImage( const Geometry &point_, const Color &fillColor_, const Color &borderColor_ ); void operator()( Image &image_ ) const; private: unsigned int _x; unsigned int _y; Color _fillColor; Color _borderColor; }; // Flood-fill image with texture class MagickDLLDecl floodFillTextureImage : public std::unary_function { public: // Flood-fill texture across pixels that match the color of the // target pixel and are neighbors of the target pixel. // Uses current fuzz setting when determining color match. floodFillTextureImage( const unsigned int x_, const unsigned int y_, const Image &texture_ ); floodFillTextureImage( const Geometry &point_, const Image &texture_ ); // Flood-fill texture across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. floodFillTextureImage( const unsigned int x_, const unsigned int y_, const Image &texture_, const Color &borderColor_ ); floodFillTextureImage( const Geometry &point_, const Image &texture_, const Color &borderColor_ ); void operator()( Image &image_ ) const; private: unsigned int _x; unsigned int _y; Image _texture; Color _borderColor; }; // Flop image (reflect each scanline in the horizontal direction) class MagickDLLDecl flopImage : public std::unary_function { public: flopImage( void ); void operator()( Image &image_ ) const; private: }; // Frame image class MagickDLLDecl frameImage : public std::unary_function { public: frameImage( const Geometry &geometry_ = frameGeometryDefault ); frameImage( const unsigned int width_, const unsigned int height_, const int innerBevel_ = 6, const int outerBevel_ = 6 ); void operator()( Image &image_ ) const; private: unsigned int _width; unsigned int _height; int _outerBevel; int _innerBevel; }; // Gamma correct image class MagickDLLDecl gammaImage : public std::unary_function { public: gammaImage( const double gamma_ ); gammaImage ( const double gammaRed_, const double gammaGreen_, const double gammaBlue_ ); void operator()( Image &image_ ) const; private: double _gammaRed; double _gammaGreen; double _gammaBlue; }; // Gaussian blur image // The number of neighbor pixels to be included in the convolution // mask is specified by 'width_'. The standard deviation of the // gaussian bell curve is specified by 'sigma_'. class MagickDLLDecl gaussianBlurImage : public std::unary_function { public: gaussianBlurImage( const double width_, const double sigma_ ); void operator()( Image &image_ ) const; private: double _width; double _sigma; }; // Implode image (special effect) class MagickDLLDecl implodeImage : public std::unary_function { public: implodeImage( const double factor_ = 50 ); void operator()( Image &image_ ) const; private: double _factor; }; // Apply a color lookup table (Hald CLUT) to the image. class MagickDLLDecl haldClutImage : public std::unary_function { public: haldClutImage( const Image &haldClutImage_ ); void operator()( Image &image_ ) const; private: Image _haldClutImage; }; // Set image validity. Valid images become empty (inValid) if // argument is false. class MagickDLLDecl isValidImage : public std::unary_function { public: isValidImage( const bool isValid_ ); void operator()( Image &image_ ) const; private: bool _isValid; }; // Label image class MagickDLLDecl labelImage : public std::unary_function { public: labelImage( const std::string &label_ ); void operator()( Image &image_ ) const; private: std::string _label; }; // Level image class MagickDLLDecl levelImage : public std::unary_function { public: levelImage( const double black_point, const double white_point, const double mid_point=1.0 ); void operator()( Image &image_ ) const; private: double _black_point; double _white_point; double _mid_point; }; // Level image channel class MagickDLLDecl levelChannelImage : public std::unary_function { public: levelChannelImage( const Magick::ChannelType channel, const double black_point, const double white_point, const double mid_point=1.0 ); void operator()( Image &image_ ) const; private: Magick::ChannelType _channel; double _black_point; double _white_point; double _mid_point; }; // Magnify image by integral size class MagickDLLDecl magnifyImage : public std::unary_function { public: magnifyImage( void ); void operator()( Image &image_ ) const; private: }; // Remap image colors with closest color from reference image class MagickDLLDecl mapImage : public std::unary_function { public: mapImage( const Image &mapImage_ , const bool dither_ = false ); void operator()( Image &image_ ) const; private: Image _mapImage; bool _dither; }; // Floodfill designated area with a matte value class MagickDLLDecl matteFloodfillImage : public std::unary_function { public: matteFloodfillImage( const Color &target_ , const unsigned int matte_, const int x_, const int y_, const PaintMethod method_ ); void operator()( Image &image_ ) const; private: Color _target; unsigned int _matte; int _x; int _y; PaintMethod _method; }; // Filter image by replacing each pixel component with the median // color in a circular neighborhood class MagickDLLDecl medianFilterImage : public std::unary_function { public: medianFilterImage( const double radius_ = 0.0 ); void operator()( Image &image_ ) const; private: double _radius; }; // Reduce image by integral size class MagickDLLDecl minifyImage : public std::unary_function { public: minifyImage( void ); void operator()( Image &image_ ) const; private: }; // Modulate percent hue, saturation, and brightness of an image. // Modulation of saturation and brightness is as a ratio of the // current value (1.0 for no change). Modulation of hue is an // absolute rotation of -180 degrees to +180 degrees from the // current position corresponding to an argument range of 0 to 2.0 // (1.0 for no change). class MagickDLLDecl modulateImage : public std::unary_function { public: modulateImage( const double brightness_, const double saturation_, const double hue_ ); void operator()( Image &image_ ) const; private: double _brightness; double _saturation; double _hue; }; // Negate colors in image. Set grayscale to only negate grayscale // values in image. class MagickDLLDecl negateImage : public std::unary_function { public: negateImage( const bool grayscale_ = false ); void operator()( Image &image_ ) const; private: bool _grayscale; }; // Normalize image (increase contrast by normalizing the pixel // values to span the full range of color values) class MagickDLLDecl normalizeImage : public std::unary_function { public: normalizeImage( void ); void operator()( Image &image_ ) const; private: }; // Oilpaint image (image looks like oil painting) class MagickDLLDecl oilPaintImage : public std::unary_function { public: oilPaintImage( const double radius_ = 3 ); void operator()( Image &image_ ) const; private: double _radius; }; // Set or attenuate the image opacity channel. If the image pixels // are opaque then they are set to the specified opacity value, // otherwise they are blended with the supplied opacity value. The // value of opacity_ ranges from 0 (completely opaque) to // MaxRGB. The defines OpaqueOpacity and TransparentOpacity are // available to specify completely opaque or completely transparent, // respectively. class MagickDLLDecl opacityImage : public std::unary_function { public: opacityImage( const unsigned int opacity_ ); void operator()( Image &image_ ) const; private: unsigned int _opacity; }; // Change color of opaque pixel to specified pen color. class MagickDLLDecl opaqueImage : public std::unary_function { public: opaqueImage( const Color &opaqueColor_, const Color &penColor_ ); void operator()( Image &image_ ) const; private: Color _opaqueColor; Color _penColor; }; // Quantize image (reduce number of colors) class MagickDLLDecl quantizeImage : public std::unary_function { public: quantizeImage( const bool measureError_ = false ); void operator()( Image &image_ ) const; private: bool _measureError; }; // Raise image (lighten or darken the edges of an image to give a // 3-D raised or lowered effect) class MagickDLLDecl raiseImage : public std::unary_function { public: raiseImage( const Geometry &geometry_ = raiseGeometryDefault, const bool raisedFlag_ = false ); void operator()( Image &image_ ) const; private: Geometry _geometry; bool _raisedFlag; }; // Reduce noise in image using a noise peak elimination filter class MagickDLLDecl reduceNoiseImage : public std::unary_function { public: reduceNoiseImage( void ); reduceNoiseImage (const unsigned int order_ ); void operator()( Image &image_ ) const; private: unsigned int _order; }; // Resize image to a certain geomtry class MagickDLLDecl resizeImage : public std::unary_function { public: resizeImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Roll image (rolls image vertically and horizontally) by specified // number of columnms and rows) class MagickDLLDecl rollImage : public std::unary_function { public: rollImage( const Geometry &roll_ ); rollImage( const int columns_, const int rows_ ); void operator()( Image &image_ ) const; private: int _columns; int _rows; }; // Rotate image counter-clockwise by specified number of degrees. class MagickDLLDecl rotateImage : public std::unary_function { public: rotateImage( const double degrees_ ); void operator()( Image &image_ ) const; private: double _degrees; }; // Resize image by using pixel sampling algorithm class MagickDLLDecl sampleImage : public std::unary_function { public: sampleImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Resize image by using simple ratio algorithm class MagickDLLDecl scaleImage : public std::unary_function { public: scaleImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Segment (coalesce similar image components) by analyzing the // histograms of the color components and identifying units that are // homogeneous with the fuzzy c-means technique. // Also uses QuantizeColorSpace and Verbose image attributes class MagickDLLDecl segmentImage : public std::unary_function { public: segmentImage( const double clusterThreshold_ = 1.0, const double smoothingThreshold_ = 1.5 ); void operator()( Image &image_ ) const; private: double _clusterThreshold; double _smoothingThreshold; }; // Shade image using distant light source class MagickDLLDecl shadeImage : public std::unary_function { public: shadeImage( const double azimuth_ = 30, const double elevation_ = 30, const bool colorShading_ = false ); void operator()( Image &image_ ) const; private: double _azimuth; double _elevation; bool _colorShading; }; // Sharpen pixels in image class MagickDLLDecl sharpenImage : public std::unary_function { public: sharpenImage( const double radius_ = 1, const double sigma_ = 0.5 ); void operator()( Image &image_ ) const; private: double _radius; double _sigma; }; // Shave pixels from image edges. class MagickDLLDecl shaveImage : public std::unary_function { public: shaveImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Shear image (create parallelogram by sliding image by X or Y axis) class MagickDLLDecl shearImage : public std::unary_function { public: shearImage( const double xShearAngle_, const double yShearAngle_ ); void operator()( Image &image_ ) const; private: double _xShearAngle; double _yShearAngle; }; // Solarize image (similar to effect seen when exposing a // photographic film to light during the development process) class MagickDLLDecl solarizeImage : public std::unary_function { public: solarizeImage( const double factor_ ); void operator()( Image &image_ ) const; private: double _factor; }; // Spread pixels randomly within image by specified ammount class MagickDLLDecl spreadImage : public std::unary_function { public: spreadImage( const unsigned int amount_ = 3 ); void operator()( Image &image_ ) const; private: unsigned int _amount; }; // Add a digital watermark to the image (based on second image) class MagickDLLDecl steganoImage : public std::unary_function { public: steganoImage( const Image &waterMark_ ); void operator()( Image &image_ ) const; private: Image _waterMark; }; // Create an image which appears in stereo when viewed with red-blue glasses // (Red image on left, blue on right) class MagickDLLDecl stereoImage : public std::unary_function { public: stereoImage( const Image &rightImage_ ); void operator()( Image &image_ ) const; private: Image _rightImage; }; // Color to use when drawing object outlines class MagickDLLDecl strokeColorImage : public std::unary_function { public: strokeColorImage( const Color &strokeColor_ ); void operator()( Image &image_ ) const; private: Color _strokeColor; }; // Swirl image (image pixels are rotated by degrees) class MagickDLLDecl swirlImage : public std::unary_function { public: swirlImage( const double degrees_ ); void operator()( Image &image_ ) const; private: double _degrees; }; // Remove all profiles and text attributes from the image. class MagickDLLDecl stripImage : public std::unary_function { public: stripImage( void ); void operator()( Image &image_ ) const; private: }; // Channel a texture on image background class MagickDLLDecl textureImage : public std::unary_function { public: textureImage( const Image &texture_ ); void operator()( Image &image_ ) const; private: Image _texture; }; // Threshold image class MagickDLLDecl thresholdImage : public std::unary_function { public: thresholdImage( const double threshold_ ); void operator()( Image &image_ ) const; private: double _threshold; }; // Transform image based on image and crop geometries class MagickDLLDecl transformImage : public std::unary_function { public: transformImage( const Geometry &imageGeometry_ ); transformImage( const Geometry &imageGeometry_, const Geometry &cropGeometry_ ); void operator()( Image &image_ ) const; private: Geometry _imageGeometry; Geometry _cropGeometry; }; // Set image color to transparent class MagickDLLDecl transparentImage : public std::unary_function { public: transparentImage( const Color& color_ ); void operator()( Image &image_ ) const; private: Color _color; }; // Trim edges that are the background color from the image class MagickDLLDecl trimImage : public std::unary_function { public: trimImage( void ); void operator()( Image &image_ ) const; private: }; // Map image pixels to a sine wave class MagickDLLDecl waveImage : public std::unary_function { public: waveImage( const double amplitude_ = 25.0, const double wavelength_ = 150.0 ); void operator()( Image &image_ ) const; private: double _amplitude; double _wavelength; }; // Zoom image to specified size. class MagickDLLDecl zoomImage : public std::unary_function { public: zoomImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // // Function object image attribute accessors // // Anti-alias Postscript and TrueType fonts (default true) class MagickDLLDecl antiAliasImage : public std::unary_function { public: antiAliasImage( const bool flag_ ); void operator()( Image &image_ ) const; private: bool _flag; }; // Join images into a single multi-image file class MagickDLLDecl adjoinImage : public std::unary_function { public: adjoinImage( const bool flag_ ); void operator()( Image &image_ ) const; private: bool _flag; }; // Time in 1/100ths of a second which must expire before displaying // the next image in an animated sequence. class MagickDLLDecl animationDelayImage : public std::unary_function { public: animationDelayImage( const unsigned int delay_ ); void operator()( Image &image_ ) const; private: unsigned int _delay; }; // Number of iterations to loop an animation (e.g. Netscape loop // extension) for. class MagickDLLDecl animationIterationsImage : public std::unary_function { public: animationIterationsImage( const unsigned int iterations_ ); void operator()( Image &image_ ) const; private: unsigned int _iterations; }; // Image background color class MagickDLLDecl backgroundColorImage : public std::unary_function { public: backgroundColorImage( const Color &color_ ); void operator()( Image &image_ ) const; private: Color _color; }; // Name of texture image to tile onto the image background class MagickDLLDecl backgroundTextureImage : public std::unary_function { public: backgroundTextureImage( const std::string &backgroundTexture_ ); void operator()( Image &image_ ) const; private: std::string _backgroundTexture; }; // Image border color class MagickDLLDecl borderColorImage : public std::unary_function { public: borderColorImage( const Color &color_ ); void operator()( Image &image_ ) const; private: Color _color; }; // Text bounding-box base color (default none) class MagickDLLDecl boxColorImage : public std::unary_function { public: boxColorImage( const Color &boxColor_ ); void operator()( Image &image_ ) const; private: Color _boxColor; }; // Chromaticity blue primary point (e.g. x=0.15, y=0.06) class MagickDLLDecl chromaBluePrimaryImage : public std::unary_function { public: chromaBluePrimaryImage( const double x_, const double y_ ); void operator()( Image &image_ ) const; private: double _x; double _y; }; // Chromaticity green primary point (e.g. x=0.3, y=0.6) class MagickDLLDecl chromaGreenPrimaryImage : public std::unary_function { public: chromaGreenPrimaryImage( const double x_, const double y_ ); void operator()( Image &image_ ) const; private: double _x; double _y; }; // Chromaticity red primary point (e.g. x=0.64, y=0.33) class MagickDLLDecl chromaRedPrimaryImage : public std::unary_function { public: chromaRedPrimaryImage( const double x_, const double y_ ); void operator()( Image &image_ ) const; private: double _x; double _y; }; // Chromaticity white point (e.g. x=0.3127, y=0.329) class MagickDLLDecl chromaWhitePointImage : public std::unary_function { public: chromaWhitePointImage( const double x_, const double y_ ); void operator()( Image &image_ ) const; private: double _x; double _y; }; // Colors within this distance are considered equal class MagickDLLDecl colorFuzzImage : public std::unary_function { public: colorFuzzImage( const double fuzz_ ); void operator()( Image &image_ ) const; private: double _fuzz; }; // Color at colormap position index_ class MagickDLLDecl colorMapImage : public std::unary_function { public: colorMapImage( const unsigned int index_, const Color &color_ ); void operator()( Image &image_ ) const; private: unsigned int _index; Color _color; }; // Composition operator to be used when composition is implicitly used // (such as for image flattening). class MagickDLLDecl composeImage : public std::unary_function { public: composeImage( const CompositeOperator compose_ ); void operator()( Image &image_ ) const; private: CompositeOperator _compose; }; // Compression type class MagickDLLDecl compressTypeImage : public std::unary_function { public: compressTypeImage( const CompressionType compressType_ ); void operator()( Image &image_ ) const; private: CompressionType _compressType; }; // Vertical and horizontal resolution in pixels of the image class MagickDLLDecl densityImage : public std::unary_function { public: densityImage( const Geometry &geomery_ ); void operator()( Image &image_ ) const; private: Geometry _geomery; }; // Image depth (bits allocated to red/green/blue components) class MagickDLLDecl depthImage : public std::unary_function { public: depthImage( const unsigned int depth_ ); void operator()( Image &image_ ) const; private: unsigned int _depth; }; // Endianness (LSBEndian like Intel or MSBEndian like SPARC) for image // formats which support endian-specific options. class MagickDLLDecl endianImage : public std::unary_function { public: endianImage( const EndianType endian_ ); void operator()( Image &image_ ) const; private: EndianType _endian; }; // Image file name class MagickDLLDecl fileNameImage : public std::unary_function { public: fileNameImage( const std::string &fileName_ ); void operator()( Image &image_ ) const; private: std::string _fileName; }; // Filter to use when resizing image class MagickDLLDecl filterTypeImage : public std::unary_function { public: filterTypeImage( const FilterTypes filterType_ ); void operator()( Image &image_ ) const; private: FilterTypes _filterType; }; // Text rendering font class MagickDLLDecl fontImage : public std::unary_function { public: fontImage( const std::string &font_ ); void operator()( Image &image_ ) const; private: std::string _font; }; // Font point size class MagickDLLDecl fontPointsizeImage : public std::unary_function { public: fontPointsizeImage( const unsigned int pointsize_ ); void operator()( Image &image_ ) const; private: unsigned int _pointsize; }; // GIF disposal method class MagickDLLDecl gifDisposeMethodImage : public std::unary_function { public: gifDisposeMethodImage( const unsigned int disposeMethod_ ); void operator()( Image &image_ ) const; private: unsigned int _disposeMethod; }; // Type of interlacing to use class MagickDLLDecl interlaceTypeImage : public std::unary_function { public: interlaceTypeImage( const InterlaceType interlace_ ); void operator()( Image &image_ ) const; private: InterlaceType _interlace; }; // Linewidth for drawing vector objects (default one) class MagickDLLDecl lineWidthImage : public std::unary_function { public: lineWidthImage( const double lineWidth_ ); void operator()( Image &image_ ) const; private: double _lineWidth; }; // File type magick identifier (.e.g "GIF") class MagickDLLDecl magickImage : public std::unary_function { public: magickImage( const std::string &magick_ ); void operator()( Image &image_ ) const; private: std::string _magick; }; // Image supports transparent color class MagickDLLDecl matteImage : public std::unary_function { public: matteImage( const bool matteFlag_ ); void operator()( Image &image_ ) const; private: bool _matteFlag; }; // Transparent color class MagickDLLDecl matteColorImage : public std::unary_function { public: matteColorImage( const Color &matteColor_ ); void operator()( Image &image_ ) const; private: Color _matteColor; }; // Indicate that image is black and white class MagickDLLDecl monochromeImage : public std::unary_function { public: monochromeImage( const bool monochromeFlag_ ); void operator()( Image &image_ ) const; private: bool _monochromeFlag; }; // Pen color class MagickDLLDecl penColorImage : public std::unary_function { public: penColorImage( const Color &penColor_ ); void operator()( Image &image_ ) const; private: Color _penColor; }; // Pen texture image. class MagickDLLDecl penTextureImage : public std::unary_function { public: penTextureImage( const Image &penTexture_ ); void operator()( Image &image_ ) const; private: Image _penTexture; }; // Set pixel color at location x & y. class MagickDLLDecl pixelColorImage : public std::unary_function { public: pixelColorImage( const unsigned int x_, const unsigned int y_, const Color &color_); void operator()( Image &image_ ) const; private: unsigned int _x; unsigned int _y; Color _color; }; // Postscript page size. class MagickDLLDecl pageImage : public std::unary_function { public: pageImage( const Geometry &pageSize_ ); void operator()( Image &image_ ) const; private: Geometry _pageSize; }; // JPEG/MIFF/PNG compression level (default 75). class MagickDLLDecl qualityImage : public std::unary_function { public: qualityImage( const unsigned int quality_ ); void operator()( Image &image_ ) const; private: unsigned int _quality; }; // Maximum number of colors to quantize to class MagickDLLDecl quantizeColorsImage : public std::unary_function { public: quantizeColorsImage( const unsigned int colors_ ); void operator()( Image &image_ ) const; private: unsigned int _colors; }; // Colorspace to quantize in. class MagickDLLDecl quantizeColorSpaceImage : public std::unary_function { public: quantizeColorSpaceImage( const ColorspaceType colorSpace_ ); void operator()( Image &image_ ) const; private: ColorspaceType _colorSpace; }; // Dither image during quantization (default true). class MagickDLLDecl quantizeDitherImage : public std::unary_function { public: quantizeDitherImage( const bool ditherFlag_ ); void operator()( Image &image_ ) const; private: bool _ditherFlag; }; // Quantization tree-depth class MagickDLLDecl quantizeTreeDepthImage : public std::unary_function { public: quantizeTreeDepthImage( const unsigned int treeDepth_ ); void operator()( Image &image_ ) const; private: unsigned int _treeDepth; }; // The type of rendering intent class MagickDLLDecl renderingIntentImage : public std::unary_function { public: renderingIntentImage( const RenderingIntent renderingIntent_ ); void operator()( Image &image_ ) const; private: RenderingIntent _renderingIntent; }; // Units of image resolution class MagickDLLDecl resolutionUnitsImage : public std::unary_function { public: resolutionUnitsImage( const ResolutionType resolutionUnits_ ); void operator()( Image &image_ ) const; private: ResolutionType _resolutionUnits; }; // Image scene number class MagickDLLDecl sceneImage : public std::unary_function { public: sceneImage( const unsigned int scene_ ); void operator()( Image &image_ ) const; private: unsigned int _scene; }; // Width and height of a raw image class MagickDLLDecl sizeImage : public std::unary_function { public: sizeImage( const Geometry &geometry_ ); void operator()( Image &image_ ) const; private: Geometry _geometry; }; // Subimage of an image sequence class MagickDLLDecl subImageImage : public std::unary_function { public: subImageImage( const unsigned int subImage_ ); void operator()( Image &image_ ) const; private: unsigned int _subImage; }; // Number of images relative to the base image class MagickDLLDecl subRangeImage : public std::unary_function { public: subRangeImage( const unsigned int subRange_ ); void operator()( Image &image_ ) const; private: unsigned int _subRange; }; // Tile name class MagickDLLDecl tileNameImage : public std::unary_function { public: tileNameImage( const std::string &tileName_ ); void operator()( Image &image_ ) const; private: std::string _tileName; }; // Image storage type class MagickDLLDecl typeImage : public std::unary_function { public: typeImage( const ImageType type_ ); void operator()( Image &image_ ) const; private: Magick::ImageType _type; }; // Print detailed information about the image class MagickDLLDecl verboseImage : public std::unary_function { public: verboseImage( const bool verbose_ ); void operator()( Image &image_ ) const; private: bool _verbose; }; // FlashPix viewing parameters class MagickDLLDecl viewImage : public std::unary_function { public: viewImage( const std::string &view_ ); void operator()( Image &image_ ) const; private: std::string _view; }; // X11 display to display to, obtain fonts from, or to capture // image from class MagickDLLDecl x11DisplayImage : public std::unary_function { public: x11DisplayImage( const std::string &display_ ); void operator()( Image &image_ ) const; private: std::string _display; }; ////////////////////////////////////////////////////////// // // Implementation template definitions. Not for end-use. // ////////////////////////////////////////////////////////// // Link images together into an image list based on the ordering of // the container implied by the iterator. This step is done in // preparation for use with ImageMagick functions which operate on // lists of images. // Images are selected by range, first_ to last_ so that a subset of // the container may be selected. Specify first_ via the // container's begin() method and last_ via the container's end() // method in order to specify the entire container. template void linkImages( InputIterator first_, InputIterator last_ ) { MagickLib::Image* previous = 0; int scene = 0; for ( InputIterator iter = first_; iter != last_; ++iter ) { // Unless we reduce the reference count to one, the same image // structure may occur more than once in the container, causing // the linked list to fail. iter->modifyImage(); MagickLib::Image* current = iter->image(); current->previous = previous; current->next = 0; current->scene = scene++; if ( previous != 0) previous->next = current; previous = current; } } // Remove links added by linkImages. This should be called after the // ImageMagick function call has completed to reset the image list // back to its pristine un-linked state. template void unlinkImages( InputIterator first_, InputIterator last_ ) { for( InputIterator iter = first_; iter != last_; ++iter ) { MagickLib::Image* image = iter->image(); image->previous = 0; image->next = 0; } } // Insert images in image list into existing container (appending to container) // The images should not be deleted since only the image ownership is passed. // The options are copied into the object. template void insertImages( Container *sequence_, MagickLib::Image* images_ ) { MagickLib::Image *image = images_; if ( image ) { do { MagickLib::Image* next_image = image->next; image->next = 0; if (next_image != 0) next_image->previous=0; sequence_->push_back( Magick::Image( image ) ); image=next_image; } while( image ); return; } } /////////////////////////////////////////////////////////////////// // // Template definitions for documented API // /////////////////////////////////////////////////////////////////// template void animateImages( InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::AnimateImages( first_->imageInfo(), first_->image() ); MagickLib::GetImageException( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } // Append images from list into single image in either horizontal or // vertical direction. template void appendImages( Image *appendedImage_, InputIterator first_, InputIterator last_, bool stack_ = false) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::Image* image = MagickLib::AppendImages( first_->image(), stack_, &exceptionInfo ); unlinkImages( first_, last_ ); appendedImage_->replaceImage( image ); throwException( exceptionInfo, appendedImage_->quiet() ); } // Average a set of images. // All the input images must be the same size in pixels. template void averageImages( Image *averagedImage_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::Image* image = MagickLib::AverageImages( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); averagedImage_->replaceImage( image ); throwException( exceptionInfo, averagedImage_->quiet() ); } // Merge a sequence of images. // This is useful for GIF animation sequences that have page // offsets and disposal methods. A container to contain // the updated image sequence is passed via the coalescedImages_ // option. template void coalesceImages( Container *coalescedImages_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); // Build image list linkImages( first_, last_ ); MagickLib::Image* images = MagickLib::CoalesceImages( first_->image(), &exceptionInfo); // Unlink image list unlinkImages( first_, last_ ); // Ensure container is empty coalescedImages_->clear(); // Move images to container insertImages( coalescedImages_, images ); // Report any error throwException( exceptionInfo, first_->quiet() ); } // Return format coders matching specified conditions. // // The default (if no match terms are supplied) is to return all // available format coders. // // For example, to return all readable formats: // list coderList; // coderInfoList( &coderList, CoderInfo::TrueMatch, CoderInfo::AnyMatch, CoderInfo::AnyMatch) // template void coderInfoList( Container *container_, CoderInfo::MatchType isReadable_ = CoderInfo::AnyMatch, CoderInfo::MatchType isWritable_ = CoderInfo::AnyMatch, CoderInfo::MatchType isMultiFrame_ = CoderInfo::AnyMatch ) { // Obtain first entry in MagickInfo list MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); MagickLib::MagickInfo **coder_list = MagickLib::GetMagickInfoArray( &exceptionInfo ); if( !coder_list ) { throwException( exceptionInfo ); throwExceptionExplicit(MagickLib::MissingDelegateError, "Coder array not returned!", 0 ); } // Clear out container container_->clear(); for ( int i=0; coder_list[i] != 0; i++) { // Skip stealth coders if ( coder_list[i]->stealth ) continue; try { CoderInfo coderInfo( coder_list[i]->name ); // Test isReadable_ if ( isReadable_ != CoderInfo::AnyMatch && (( coderInfo.isReadable() && isReadable_ != CoderInfo::TrueMatch ) || ( !coderInfo.isReadable() && isReadable_ != CoderInfo::FalseMatch )) ) continue; // Test isWritable_ if ( isWritable_ != CoderInfo::AnyMatch && (( coderInfo.isWritable() && isWritable_ != CoderInfo::TrueMatch ) || ( !coderInfo.isWritable() && isWritable_ != CoderInfo::FalseMatch )) ) continue; // Test isMultiFrame_ if ( isMultiFrame_ != CoderInfo::AnyMatch && (( coderInfo.isMultiFrame() && isMultiFrame_ != CoderInfo::TrueMatch ) || ( !coderInfo.isMultiFrame() && isMultiFrame_ != CoderInfo::FalseMatch )) ) continue; // Append matches to container container_->push_back( coderInfo ); } // Intentionally ignore missing module errors catch ( Magick::ErrorModule & ) { continue; } } MagickLib::MagickFree(coder_list); coder_list=0; MagickLib::DestroyExceptionInfo( &exceptionInfo ); } // // Fill container with color histogram. // Entries are of type "std::pair". Use the pair // "first" member to access the Color and the "second" member to access // the number of times the color occurs in the image. // // For example: // // Using : // // Image image("image.miff"); // map histogram; // colorHistogram( &histogram, image ); // std::map::const_iterator p=histogram.begin(); // while (p != histogram.end()) // { // cout << setw(10) << (int)p->second << ": (" // << setw(quantum_width) << (int)p->first.redQuantum() << "," // << setw(quantum_width) << (int)p->first.greenQuantum() << "," // << setw(quantum_width) << (int)p->first.blueQuantum() << ")" // << endl; // p++; // } // // Using : // // Image image("image.miff"); // std::vector > histogram; // colorHistogram( &histogram, image ); // std::vector >::const_iterator p=histogram.begin(); // while (p != histogram.end()) // { // cout << setw(10) << (int)p->second << ": (" // << setw(quantum_width) << (int)p->first.redQuantum() << "," // << setw(quantum_width) << (int)p->first.greenQuantum() << "," // << setw(quantum_width) << (int)p->first.blueQuantum() << ")" // << endl; // p++; // } template void colorHistogram( Container *histogram_, const Image image) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); // Obtain histogram array unsigned long colors; MagickLib::HistogramColorPacket *histogram_array = MagickLib::GetColorHistogram( image.constImage(), &colors, &exceptionInfo ); throwException( exceptionInfo, image.quiet() ); // Clear out container histogram_->clear(); // Transfer histogram array to container for ( unsigned long i=0; i < colors; i++) { histogram_->insert(histogram_->end(),std::pair ( Color(histogram_array[i].pixel.red, histogram_array[i].pixel.green, histogram_array[i].pixel.blue), histogram_array[i].count) ); } // Deallocate histogram array MagickLib::MagickFree(histogram_array); histogram_array = 0; } // Break down an image sequence into constituent parts. This is // useful for creating GIF or MNG animation sequences. template void deconstructImages( Container *deconstructedImages_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); // Build image list linkImages( first_, last_ ); MagickLib::Image* images = MagickLib::DeconstructImages( first_->image(), &exceptionInfo); // Unlink image list unlinkImages( first_, last_ ); // Ensure container is empty deconstructedImages_->clear(); // Move images to container insertImages( deconstructedImages_, images ); // Report any error throwException( exceptionInfo, first_->quiet() ); } // // Display an image sequence // template void displayImages( InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::DisplayImages( first_->imageInfo(), first_->image() ); MagickLib::GetImageException( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } // Merge a sequence of image frames which represent image layers. // This is useful for combining Photoshop layers into a single image. template void flattenImages( Image *flattendImage_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::Image* image = MagickLib::FlattenImages( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); flattendImage_->replaceImage( image ); throwException( exceptionInfo, flattendImage_->quiet() ); } // Replace the colors of a sequence of images with the closest color // from a reference image. // Set dither_ to true to enable dithering. Set measureError_ to // true in order to evaluate quantization error. template void mapImages( InputIterator first_, InputIterator last_, const Image& mapImage_, bool dither_ = false, bool measureError_ = false ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::MapImages( first_->image(), mapImage_.constImage(), dither_ ); MagickLib::GetImageException( first_->image(), &exceptionInfo ); if ( exceptionInfo.severity != MagickLib::UndefinedException ) { unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } MagickLib::Image* image = first_->image(); while( image ) { // Calculate quantization error if ( measureError_ ) { MagickLib::GetImageQuantizeError( image ); if ( image->exception.severity > MagickLib::UndefinedException ) { unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } } // Udate DirectClass representation of pixels MagickLib::SyncImage( image ); if ( image->exception.severity > MagickLib::UndefinedException ) { unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } // Next image image=image->next; } unlinkImages( first_, last_ ); } // Create a composite image by combining several separate images. template void montageImages( Container *montageImages_, InputIterator first_, InputIterator last_, const Montage &montageOpts_ ) { MagickLib::MontageInfo* montageInfo = static_cast(MagickLib::MagickMalloc(sizeof(MagickLib::MontageInfo))); // Update montage options with those set in montageOpts_ montageOpts_.updateMontageInfo( *montageInfo ); // Update options which must transfer to image options if ( montageOpts_.label().length() != 0 ) first_->label( montageOpts_.label() ); // Create linked image list linkImages( first_, last_ ); // Reset output container to pristine state montageImages_->clear(); // Do montage MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); MagickLib::Image *images = MagickLib::MontageImages( first_->image(), montageInfo, &exceptionInfo ); if ( images != 0 ) { insertImages( montageImages_, images ); } // Clean up any allocated data in montageInfo MagickLib::DestroyMontageInfo( montageInfo ); // Unlink linked image list unlinkImages( first_, last_ ); // Report any montage error throwException( exceptionInfo, first_->quiet() ); // Apply transparency to montage images if ( montageImages_->size() > 0 && montageOpts_.transparentColor().isValid() ) { for_each( first_, last_, transparentImage( montageOpts_.transparentColor() ) ); } // Report any transparentImage() error MagickLib::GetImageException( first_->image(), &exceptionInfo ); throwException( exceptionInfo, first_->quiet() ); } // Morph a set of images template void morphImages( Container *morphedImages_, InputIterator first_, InputIterator last_, unsigned int frames_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); // Build image list linkImages( first_, last_ ); MagickLib::Image* images = MagickLib::MorphImages( first_->image(), frames_, &exceptionInfo); // Unlink image list unlinkImages( first_, last_ ); // Ensure container is empty morphedImages_->clear(); // Move images to container insertImages( morphedImages_, images ); // Report any error throwException( exceptionInfo, first_->quiet() ); } // Inlay a number of images to form a single coherent picture. template void mosaicImages( Image *mosaicImage_, InputIterator first_, InputIterator last_ ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::Image* image = MagickLib::MosaicImages( first_->image(), &exceptionInfo ); unlinkImages( first_, last_ ); mosaicImage_->replaceImage( image ); throwException( exceptionInfo, first_->quiet() ); } // Quantize colors in images using current quantization settings // Set measureError_ to true in order to measure quantization error template void quantizeImages( InputIterator first_, InputIterator last_, bool measureError_ = false ) { MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); MagickLib::QuantizeImages( first_->quantizeInfo(), first_->image() ); MagickLib::GetImageException( first_->image(), &exceptionInfo ); if ( exceptionInfo.severity > MagickLib::UndefinedException ) { unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } MagickLib::Image* image = first_->image(); while( image != 0 ) { // Calculate quantization error if ( measureError_ ) MagickLib::GetImageQuantizeError( image ); // Update DirectClass representation of pixels MagickLib::SyncImage( image ); // Next image image=image->next; } unlinkImages( first_, last_ ); } // Read images into existing container (appending to container) // FIXME: need a way to specify options like size, depth, and density. template void readImages( Container *sequence_, const std::string &imageSpec_ ) { MagickLib::ImageInfo *imageInfo = MagickLib::CloneImageInfo(0); imageSpec_.copy( imageInfo->filename, MaxTextExtent-1 ); imageInfo->filename[ imageSpec_.length() ] = 0; MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); MagickLib::Image* images = MagickLib::ReadImage( imageInfo, &exceptionInfo ); MagickLib::DestroyImageInfo(imageInfo); insertImages( sequence_, images); throwException( exceptionInfo ); } template void readImages( Container *sequence_, const Blob &blob_ ) { MagickLib::ImageInfo *imageInfo = MagickLib::CloneImageInfo(0); MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); MagickLib::Image *images = MagickLib::BlobToImage( imageInfo, blob_.data(), blob_.length(), &exceptionInfo ); MagickLib::DestroyImageInfo(imageInfo); insertImages( sequence_, images ); throwException( exceptionInfo ); } // Write Images // // If an attribute is not supported as an explicit argument // (e.g. 'magick'), then the attribute must be set on the involved // images in the container prior to invoking writeImages() since // attributes from the individual images are the ones which are // used. template void writeImages( InputIterator first_, InputIterator last_, const std::string &imageSpec_, bool adjoin_ = true ) { first_->adjoin( adjoin_ ); MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); linkImages( first_, last_ ); int errorStat = MagickLib::WriteImages( first_->constImageInfo(), first_->image(), imageSpec_.c_str(), &exceptionInfo ); unlinkImages( first_, last_ ); if ( errorStat != false ) { MagickLib::DestroyExceptionInfo( &exceptionInfo ); return; } throwException( exceptionInfo, first_->quiet() ); } // Write images to BLOB // // If an attribute is not supported as an explicit argument // (e.g. 'magick'), then the attribute must be set on the involved // images in the container prior to invoking writeImages() since // attributes from the individual images are the ones which are // used. template void writeImages( InputIterator first_, InputIterator last_, Blob *blob_, bool adjoin_ = true) { first_->adjoin( adjoin_ ); linkImages( first_, last_ ); MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo( &exceptionInfo ); size_t length = 2048; // Efficient size for small images void* data = MagickLib::ImageToBlob( first_->imageInfo(), first_->image(), &length, &exceptionInfo); blob_->updateNoCopy( data, length, Magick::Blob::MallocAllocator ); unlinkImages( first_, last_ ); throwException( exceptionInfo, first_->quiet() ); } } // namespace Magick #endif // Magick_STL_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++/TypeMetric.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 2001, 2002 // // TypeMetric Definition // // Container for font type metrics // #if !defined (Magick_TypeMetric_header) #define Magick_TypeMetric_header #include "Magick++/Include.h" namespace Magick { class MagickDLLDecl TypeMetric { friend class Image; public: TypeMetric ( void ); ~TypeMetric ( void ); // Ascent, the distance in pixels from the text baseline to the // highest/upper grid coordinate used to place an outline point. double ascent ( void ) const; // Descent, the distance in pixels from the baseline to the lowest // grid coordinate used to place an outline point. Always a // negative value. double descent ( void ) const; // Text width in pixels. double textWidth ( void ) const; // Text height in pixels. double textHeight ( void ) const; // Maximum horizontal advance in pixels. double maxHorizontalAdvance ( void ) const; // // Public methods below this point are for Magick++ use only. // private: MagickLib::TypeMetric _typeMetric; }; } // namespace Magick // // Inlines // #endif // Magick_TypeMetric_header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/Magick++.h ================================================ // This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000 // // Simplified includes for Magick++. // Inclusion of this header is sufficient to use all Magick++ APIs. // #ifndef MagickPlusPlus_Header #include #include #include #include #define MagickPlusPlus_Header #endif // MagickPlusPlus_Header ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/analyze.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Analysis Methods. */ #ifndef _MAGICK_ANALYZE_H #define _MAGICK_ANALYZE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ #include "magick/image.h" typedef struct _ImageCharacteristics { MagickBool cmyk, /* CMYK(A) image */ grayscale, /* Grayscale image */ monochrome, /* Black/white image */ opaque, /* Opaque image */ palette; /* Colormapped image */ } ImageCharacteristics; /* Functions which return unsigned int to indicate operation pass/fail */ extern MagickExport MagickPassFail GetImageCharacteristics(const Image *image,ImageCharacteristics *characteristics, const MagickBool optimize,ExceptionInfo *exception); extern MagickExport unsigned long GetImageDepth(const Image *,ExceptionInfo *); extern MagickExport MagickBool IsGrayImage(const Image *image,ExceptionInfo *exception), IsMonochromeImage(const Image *image,ExceptionInfo *exception), IsOpaqueImage(const Image *image,ExceptionInfo *exception); extern MagickExport ImageType GetImageType(const Image *,ExceptionInfo *); extern MagickExport RectangleInfo GetImageBoundingBox(const Image *,ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_ANALYZE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/api.h ================================================ /* Copyright (C) 2003 - 2012 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Application Programming Interface declarations. */ #if !defined(_MAGICK_API_H) #define _MAGICK_API_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/magick_config.h" #if defined(__cplusplus) || defined(c_plusplus) # undef inline #endif #include #include #include #include /* POSIX 1990 header and declares size_t and ssize_t */ /* Note that the WIN32 and WIN64 definitions are provided by the build configuration rather than the compiler. Definitions available from the Windows compiler are _WIN32 and _WIN64. */ #if defined(WIN32) || defined(WIN64) # define MSWINDOWS #endif /* defined(WIN32) || defined(WIN64) */ #if defined(MAGICK_IMPLEMENTATION) # if defined(MSWINDOWS) /* Use Visual C++ C inline method extension to improve performance */ # if !defined(inline) && !defined(__cplusplus) && !defined(c_plusplus) # define inline __inline # endif # endif #endif #if defined(PREFIX_MAGICK_SYMBOLS) # include "magick/symbols.h" #endif /* defined(PREFIX_MAGICK_SYMBOLS) */ #include "magick/common.h" #include "magick/magick_types.h" #include "magick/analyze.h" #include "magick/attribute.h" #include "magick/average.h" #include "magick/blob.h" #include "magick/cdl.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color_lookup.h" #include "magick/colormap.h" #include "magick/command.h" #include "magick/compare.h" #include "magick/composite.h" #include "magick/compress.h" #include "magick/confirm_access.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/delegate.h" #include "magick/deprecate.h" #include "magick/describe.h" #include "magick/draw.h" #include "magick/effect.h" #include "magick/enhance.h" #include "magick/error.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/gradient.h" #include "magick/hclut.h" #include "magick/image.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/montage.h" #include "magick/operator.h" #include "magick/paint.h" #include "magick/pixel_cache.h" #include "magick/pixel_iterator.h" #include "magick/plasma.h" #include "magick/profile.h" #include "magick/quantize.h" /*#include "magick/random.h"*/ #include "magick/registry.h" #include "magick/render.h" #include "magick/resize.h" #include "magick/resource.h" #include "magick/shear.h" #include "magick/signature.h" #include "magick/statistics.h" #include "magick/texture.h" #include "magick/timer.h" #include "magick/transform.h" #include "magick/type.h" #include "magick/utility.h" #include "magick/version.h" #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_API_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/attribute.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Methods to Get/Set/Destroy Image Text Attributes. */ #ifndef _MAGICK_ATTRIBUTE_H #define _MAGICK_ATTRIBUTE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/image.h" typedef struct _ImageAttribute { char *key, /* identifying key */ *value; /* value string */ size_t length; /* value string length */ struct _ImageAttribute *previous, *next; } ImageAttribute; /* MagickExported text attribute methods. */ extern MagickExport const ImageAttribute *GetImageAttribute(const Image *image,const char *key), *GetImageClippingPathAttribute(const Image *image), *GetImageInfoAttribute(const ImageInfo *image_info,const Image *image,const char *key); extern MagickExport MagickPassFail CloneImageAttributes(Image* clone_image, const Image* original_image), SetImageAttribute(Image *image,const char *key,const char *value); extern MagickExport void DestroyImageAttributes(Image *image); #if defined(MAGICK_IMPLEMENTATION) # include "magick/attribute-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/average.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Averaging Methods. */ #ifndef _MAGICK_AVERAGE_H #define _MAGICK_AVERAGE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" extern MagickExport Image *AverageImages(const Image *,ExceptionInfo *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_AVERAGE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/blob.h ================================================ /* Copyright (C) 2003-2018 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Image Compression/Decompression Methods. */ #ifndef _MAGICK_BLOB_H #define _MAGICK_BLOB_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/image.h" /* Minimum input file size before considering for memory map. */ #define MinBlobExtent 32768L /* Forward declarations. */ typedef struct _BlobInfo BlobInfo; /* * * BlobInfo methods * */ /* Makes a duplicate of the given blob info structure, or if blob info is NULL, a new one. */ extern MagickExport BlobInfo* CloneBlobInfo(const BlobInfo *blob_info); /* Increments the reference count associated with the pixel blob, returning a pointer to the blob. */ extern MagickExport BlobInfo* ReferenceBlob(BlobInfo *blob); /* Deallocate memory associated with the BlobInfo structure. */ extern MagickExport void DestroyBlobInfo(BlobInfo *blob) MAGICK_FUNC_DEPRECATED; /* If BLOB is a memory mapping then unmap it. Reset BlobInfo structure to its default state. */ extern MagickExport void DetachBlob(BlobInfo *blob); /* Initialize a BlobInfo structure. */ extern MagickExport void GetBlobInfo(BlobInfo *blob); /* Attach memory buffer to a BlobInfo structure. */ extern MagickExport void AttachBlob(BlobInfo *blob_info, const void *blob, const size_t length); /* * * Functions for managing a BLOB (type BlobInfo) attached to an Image. * */ /* Deallocate all memory associated with an Image blob (reference counted). */ extern MagickExport void DestroyBlob(Image *image); /* * * Formatted image I/O functions * */ /* Read an Image from a formatted in-memory "file" image ("BLOB"). */ extern MagickExport Image* BlobToImage(const ImageInfo *image_info, const void *blob, const size_t length, ExceptionInfo *exception); /* Return an Image populated with salient information regarding a formatted in-memory "file" image ("BLOB") but without reading the image pixels. */ extern MagickExport Image* PingBlob(const ImageInfo *image_info, const void *blob, const size_t length, ExceptionInfo *exception); /* Writes an Image to a formatted (like a file) in-memory representation. */ extern MagickExport void *ImageToBlob(const ImageInfo *image_info, Image *image, size_t *length, ExceptionInfo *exception); /* * * Core File or BLOB I/O functions. * */ /* Blob open modes. */ typedef enum { UndefinedBlobMode, /* Undefined */ ReadBlobMode, /* Open for reading (text) */ /* only locale.c */ ReadBinaryBlobMode, /* Open for reading (binary) */ WriteBlobMode, /* Open for writing (text) */ /* only mvg.c txt.c */ WriteBinaryBlobMode /* Open for writing (binary) */ } BlobMode; /* Open an input or output stream for access. May also use a stream provided via image_info->stream. */ extern MagickExport MagickPassFail OpenBlob(const ImageInfo *image_info, Image *image, const BlobMode mode, ExceptionInfo *exception); /* Close I/O to the file or BLOB. */ extern MagickExport MagickPassFail CloseBlob(Image *image); /* Read data from the file or BLOB into a buffer. */ extern MagickExport size_t ReadBlob(Image *image, const size_t length, void *data); /* Read data from the file or BLOB into a buffer, but support zero-copy if possible. */ extern MagickExport size_t ReadBlobZC(Image *image, const size_t length, void **data); /* Write data from a buffer to the file or BLOB. */ extern MagickExport size_t WriteBlob(Image *image, const size_t length, const void *data); /* Move the current read or write offset position in the file or BLOB. */ extern MagickExport magick_off_t SeekBlob(Image *image, const magick_off_t offset, const int whence); /* Obtain the current read or write offset position in the file or BLOB. */ extern MagickExport magick_off_t TellBlob(const Image *image); /* Test to see if EOF has been detected while reading the file or BLOB. */ extern MagickExport int EOFBlob(const Image *image); /* Test to see if an error has been encountered while doing I/O to the file or BLOB. Non-zero is returned if an error occured. */ extern MagickExport int GetBlobStatus(const Image *image) MAGICK_FUNC_PURE; /* Return the first errno present when an error has been encountered while doing I/O to the file or BLOB. This is only useful if GetBlobStatus() has already reported that an error occured. */ extern MagickExport int GetBlobFirstErrno(const Image *image) MAGICK_FUNC_PURE; /* Test to see if blob is currently open. */ extern MagickExport MagickBool GetBlobIsOpen(const Image *image) MAGICK_FUNC_PURE; /* Obtain the current size of the file or BLOB. Zero is returned if the size can not be determined. If BLOB is no longer open, then return the size when the BLOB was closed. */ extern MagickExport magick_off_t GetBlobSize(const Image *image); /* Obtain the underlying stdio FILE* for the file (if any). */ extern MagickExport FILE *GetBlobFileHandle(const Image *image) MAGICK_FUNC_PURE; /* Obtain a pointer to the base of where BLOB data is stored. The data is only available if the data is stored on the heap, or is memory mapped. Otherwise NULL is returned. */ extern MagickExport unsigned char *GetBlobStreamData(const Image *image) MAGICK_FUNC_PURE; /* * * Formatted File or BLOB I/O functions. * */ /* Read a single byte from the file or BLOB. Returns an EOF character if EOF has been detected. */ extern MagickExport int ReadBlobByte(Image *image); /* Read a 16-bit little-endian unsigned "short" value from the file or BLOB. */ extern MagickExport magick_uint16_t ReadBlobLSBShort(Image *image); /* Read a 16-bit little-endian signed "short" value from the file or BLOB. */ extern MagickExport magick_int16_t ReadBlobLSBSignedShort(Image *image); /* Read an array of little-endian unsigned 16-bit "short" values from the file or BLOB. */ extern MagickExport size_t ReadBlobLSBShorts(Image *image, size_t octets, magick_uint16_t *data); /* Read a 16-bit big-endian unsigned "short" value from the file or BLOB. */ extern MagickExport magick_uint16_t ReadBlobMSBShort(Image *image); /* Read a 16-bit big-endian signed "short" value from the file or BLOB. */ extern MagickExport magick_int16_t ReadBlobMSBSignedShort(Image *image); /* Read an array of big-endian 16-bit "short" values from the file or BLOB. */ extern MagickExport size_t ReadBlobMSBShorts(Image *image, size_t octets, magick_uint16_t *data); /* Read a 32-bit little-endian unsigned "long" value from the file or BLOB. */ extern MagickExport magick_uint32_t ReadBlobLSBLong(Image *image); /* Read a 32-bit little-endian signed "long" value from the file or BLOB. */ extern MagickExport magick_int32_t ReadBlobLSBSignedLong(Image *image); /* Read an array of little-endian 32-bit "long" values from the file or BLOB. */ extern MagickExport size_t ReadBlobLSBLongs(Image *image, size_t octets, magick_uint32_t *data); /* Read a 32-bit big-endian unsigned "long" value from the file or BLOB. */ extern MagickExport magick_uint32_t ReadBlobMSBLong(Image *image); /* Read a 32-bit big-endian signed "long" value from the file or BLOB. */ extern MagickExport magick_int32_t ReadBlobMSBSignedLong(Image *image); /* Read an array of big-endian 32-bit "long" values from the file or BLOB. */ extern MagickExport size_t ReadBlobMSBLongs(Image *image, size_t octets, magick_uint32_t *data); /* Read a little-endian 32-bit "float" value from the file or BLOB. */ extern MagickExport float ReadBlobLSBFloat(Image *image); /* Read an array of little-endian 32-bit "float" values from the file or BLOB. */ extern MagickExport size_t ReadBlobLSBFloats(Image *image, size_t octets, float *data); /* Read a big-endian 32-bit "float" value from the file or BLOB. */ extern MagickExport float ReadBlobMSBFloat(Image *image); /* Read an array of big-endian 32-bit "float" values from the file or BLOB. */ extern MagickExport size_t ReadBlobMSBFloats(Image *image, size_t octets, float *data); /* Read a little-endian 64-bit "double" value from the file or BLOB. */ extern MagickExport double ReadBlobLSBDouble(Image *image); /* Read an array of little-endian 64-bit "double" values from the file or BLOB. */ extern MagickExport size_t ReadBlobLSBDoubles(Image *image, size_t octets, double *data); /* Read a big-endian 64-bit "double" value from the file or BLOB. */ extern MagickExport double ReadBlobMSBDouble(Image *image); /* Read an array of big-endian 64-bit "double" values from the file or BLOB. */ extern MagickExport size_t ReadBlobMSBDoubles(Image *image, size_t octets, double *data); /* Read a string from the file or blob until a newline character is read or an end-of-file condition is encountered. */ extern MagickExport char *ReadBlobString(Image *image, char *string); /* Write a single byte to the file or BLOB. */ extern MagickExport size_t WriteBlobByte(Image *image, const magick_uint8_t value); /* Write the content of an entire disk file to the file or BLOB. */ extern MagickExport MagickPassFail WriteBlobFile(Image *image, const char *filename); /* Write a 16-bit signed "short" value to the file or BLOB in little-endian order. */ extern MagickExport size_t WriteBlobLSBShort(Image *image, const magick_uint16_t value); /* Write a 16-bit signed "short" value to the file or BLOB in little-endian order. */ extern MagickExport size_t WriteBlobLSBSignedShort(Image *image, const magick_int16_t value); /* Write a 32-bit unsigned "long" value to the file or BLOB in little-endian order. */ extern MagickExport size_t WriteBlobLSBLong(Image *image, const magick_uint32_t value); /* Write a 32-bit signed "long" value to the file or BLOB in little-endian order. */ extern MagickExport size_t WriteBlobLSBSignedLong(Image *image, const magick_int32_t value); /* Write a 32-bit unsigned "long" value to the file or BLOB in big-endian order. */ extern MagickExport size_t WriteBlobMSBLong(Image *image, const magick_uint32_t value); /* Write a 32-bit signed "long" value to the file or BLOB in big-endian order. */ extern MagickExport size_t WriteBlobMSBSignedLong(Image *image, const magick_int32_t value); /* Write a 16-bit unsigned "short" value to the file or BLOB in big-endian order. */ extern MagickExport size_t WriteBlobMSBShort(Image *image, const magick_uint16_t value); /* Write a 16-bit signed "short" value to the file or BLOB in big-endian order. */ extern MagickExport size_t WriteBlobMSBSignedShort(Image *image, const magick_int16_t value); /* Write a C string to the file or BLOB, without the terminating NULL byte. */ extern MagickExport size_t WriteBlobString(Image *image, const char *string); /* * * BLOB attribute access. * */ /* Blob supports seek operations. BlobSeek() and BlobTell() may safely be used. */ extern MagickExport MagickBool BlobIsSeekable(const Image *image) MAGICK_FUNC_PURE; /* Allow file descriptor to be closed (if True). */ extern MagickExport void SetBlobClosable(Image *image, MagickBool closable); /* Blob is for a temporary file which should be deleted (if True). */ extern MagickExport void SetBlobTemporary(Image *image, MagickBool isTemporary); /* Returns MagickTrue if the file associated with the blob is a temporary file and should be removed when the associated image is destroyed. */ extern MagickExport MagickBool GetBlobTemporary(const Image *image) MAGICK_FUNC_PURE; /* * * Memory mapped file support. * */ /* Memory mapping modes. */ typedef enum { ReadMode, /* Map for read-only access */ WriteMode, /* Map for write-only access (useless) */ IOMode /* Map for read/write access */ } MapMode; /* Release memory mapping for a region. */ extern MagickExport MagickPassFail UnmapBlob(void *map, const size_t length); /* Perform a requested memory mapping of a file descriptor. */ extern MagickExport void *MapBlob(int file, const MapMode mode, magick_off_t offset, size_t length); /* * * Buffer to File / File to Buffer functions. * */ /* Writes a buffer to a named file. */ extern MagickExport MagickPassFail BlobToFile(const char *filename, const void *blob, const size_t length, ExceptionInfo *exception); /* Read the contents of a file into memory. */ extern MagickExport void *FileToBlob(const char *filename, size_t *length, ExceptionInfo *exception); /* * * Junk yet to be categorized. * */ /* Reserve space for a specified output size. */ extern MagickExport MagickPassFail BlobReserveSize(Image *image, magick_off_t size); /* Copies data from the input stream to a file. Useful in case it is necessary to perform seek operations on the input data. */ extern MagickExport MagickPassFail ImageToFile(Image *image, const char *filename, ExceptionInfo *exception); /* Search for a configuration file (".mgk" file) using appropriate rules and return as an in-memory buffer. */ extern MagickExport void *GetConfigureBlob(const char *filename, char *path, size_t *length, ExceptionInfo *exception); /* Converts a least-significant byte first buffer of integers to most-significant byte first. */ extern MagickExport void MSBOrderLong(unsigned char *buffer, const size_t length); /* Converts a least-significant byte first buffer of integers to most-significant byte first. */ extern MagickExport void MSBOrderShort(unsigned char *p, const size_t length); /* Checks if the blob of the specified image is referenced by other images. If the reference count is higher then 1 a new blob is assigned to the image. */ extern MagickExport void DisassociateBlob(Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/cdl.h ================================================ /* * Copyright (C) 2009 GraphicsMagick Group * * American Society of Cinematographers Color Decision List (ASC-CDL) * implementation. * * Original implementation by Clment Follet. */ #ifndef _MAGICK_CDL_H #define _MAGICK_CDL_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport MagickPassFail CdlImage(Image *image,const char *cdl); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_CDL_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/channel.h ================================================ /* Copyright (C) 2004 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. */ #ifndef _MAGICK_CHANNEL_H #define _MAGICK_CHANNEL_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif extern MagickExport Image *ExportImageChannel(const Image *image, const ChannelType channel, ExceptionInfo *exception); extern MagickExport unsigned int GetImageChannelDepth(const Image *image, const ChannelType channel, ExceptionInfo *exception); extern MagickExport MagickPassFail ChannelImage(Image *image,const ChannelType channel), ImportImageChannel(const Image *src_image, Image *dst_image, const ChannelType channel), ImportImageChannelsMasked(const Image *source_image, Image *update_image, const ChannelType channels), SetImageChannelDepth(Image *image, const ChannelType channel, const unsigned int depth); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_CHANNEL_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/color.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Color Utility Methods. */ #ifndef _MAGICK_COLOR_H #define _MAGICK_COLOR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* PixelPacket with usage count, used to support color histograms. */ typedef struct _HistogramColorPacket { PixelPacket pixel; unsigned long count; } HistogramColorPacket; extern MagickExport HistogramColorPacket *GetColorHistogram(const Image *image,unsigned long *colors, ExceptionInfo *exception); extern MagickExport unsigned long GetNumberColors(const Image *image,FILE *file,ExceptionInfo *exception); extern MagickExport void GetColorTuple(const PixelPacket *color,const unsigned int depth, const unsigned int matte,const unsigned int hex,char *tuple); extern MagickExport MagickBool IsPaletteImage(const Image *image,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) # include "magick/color-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_COLOR_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/color_lookup.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Color Lookup Methods. */ #ifndef _MAGICK_COLOR_LOOKUP_H #define _MAGICK_COLOR_LOOKUP_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Specifications that color is compliant with. */ typedef enum { UndefinedCompliance = 0x0000, NoCompliance = 0x0000, SVGCompliance = 0x0001, X11Compliance = 0x0002, XPMCompliance = 0x0004, AllCompliance = 0xffff } ComplianceType; extern MagickExport char **GetColorList(const char *pattern,unsigned long *number_colors); extern MagickExport unsigned int QueryColorDatabase(const char *name,PixelPacket *color,ExceptionInfo *exception), QueryColorname(const Image *image,const PixelPacket *color, const ComplianceType compliance,char *name,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) # include "magick/color_lookup-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_COLOR_LOOKUP_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/colormap.h ================================================ /* Copyright (C) 2003 - 2019 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Colormap Methods */ #ifndef _MAGICK_COLORMAP_H #define _MAGICK_COLORMAP_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" extern MagickExport MagickPassFail AllocateImageColormap(Image *,const unsigned long colors), CycleColormapImage(Image *image,const int amount), ReallocateImageColormap(Image *,const unsigned int colors), ReplaceImageColormap(Image *image,const PixelPacket *colormap, const unsigned int colors), SortColormapByIntensity(Image *image); #if defined(MAGICK_IMPLEMENTATION) # include "magick/colormap-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_COLORMAP_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/colorspace.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Colorspace Methods. */ #ifndef _MAGICK_COLORSPACE_H #define _MAGICK_COLORSPACE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (QuantumDepth == 8) || (QuantumDepth == 16) /* intensity=0.299*red+0.587*green+0.114*blue. Premultiply by 1024 to obtain integral values, and then divide result by 1024 by shifting to the right by 10 bits. */ #define PixelIntensityRec601(pixel) \ ((unsigned int) \ (((unsigned int) (pixel)->red*306U+ \ (unsigned int) (pixel)->green*601U+ \ (unsigned int) (pixel)->blue*117U) \ >> 10U)) #elif (QuantumDepth == 32) /* intensity=0.299*red+0.587*green+0.114*blue. */ #define PixelIntensityRec601(pixel) \ ((unsigned int) \ (((double)306.0*(pixel)->red+ \ (double)601.0*(pixel)->green+ \ (double)117.0*(pixel)->blue) \ / 1024.0)) #endif /* intensity=0.2126*red+0.7152*green+0.0722*blue */ #define PixelIntensityRec709(pixel) \ ((unsigned int) \ (0.2126*(pixel)->red+ \ 0.7152*(pixel)->green+ \ 0.0722*(pixel)->blue)) #define PixelIntensity(pixel) PixelIntensityRec601(pixel) #define PixelIntensityToDouble(pixel) ((double)PixelIntensity(pixel)) #define PixelIntensityToQuantum(pixel) ((Quantum)PixelIntensity(pixel)) #define IsCMYKColorspace(colorspace) \ ( \ (colorspace == CMYKColorspace) \ ) #define IsGrayColorspace(colorspace) \ ( \ (colorspace == GRAYColorspace) || \ (colorspace == Rec601LumaColorspace) || \ (colorspace == Rec709LumaColorspace) \ ) #define IsRGBColorspace(colorspace) \ ( \ (IsGrayColorspace(colorspace)) || \ (colorspace == RGBColorspace) || \ (colorspace == TransparentColorspace) \ ) #define IsLABColorspace(colorspace) \ ( \ (colorspace == LABColorspace) \ ) #define IsRGBCompatibleColorspace(colorspace) \ ( \ (IsRGBColorspace(colorspace)) || \ (colorspace == CineonLogRGBColorspace ) \ ) #define IsYCbCrColorspace(colorspace) \ ( \ (colorspace == YCbCrColorspace) || \ (colorspace == Rec601YCbCrColorspace) || \ (colorspace == Rec709YCbCrColorspace) \ ) #define YCbCrColorspace Rec601YCbCrColorspace typedef enum { UndefinedColorspace, RGBColorspace, /* Plain old RGB colorspace */ GRAYColorspace, /* Plain old full-range grayscale */ TransparentColorspace, /* RGB but preserve matte channel during quantize */ OHTAColorspace, XYZColorspace, /* CIE XYZ */ YCCColorspace, /* Kodak PhotoCD PhotoYCC */ YIQColorspace, YPbPrColorspace, YUVColorspace, CMYKColorspace, /* Cyan, magenta, yellow, black, alpha */ sRGBColorspace, /* Kodak PhotoCD sRGB */ HSLColorspace, /* Hue, saturation, luminosity */ HWBColorspace, /* Hue, whiteness, blackness */ LABColorspace, /* LAB colorspace not supported yet other than via lcms */ CineonLogRGBColorspace,/* RGB data with Cineon Log scaling, 2.048 density range */ Rec601LumaColorspace, /* Luma (Y) according to ITU-R 601 */ Rec601YCbCrColorspace, /* YCbCr according to ITU-R 601 */ Rec709LumaColorspace, /* Luma (Y) according to ITU-R 709 */ Rec709YCbCrColorspace /* YCbCr according to ITU-R 709 */ } ColorspaceType; extern MagickExport MagickPassFail RGBTransformImage(ImagePtr,const ColorspaceType), TransformColorspace(ImagePtr,const ColorspaceType), TransformRGBImage(ImagePtr,const ColorspaceType); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_COLORSPACE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/command.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Image Command Methods. */ #ifndef _MAGICK_COMMAND_H #define _MAGICK_COMMAND_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif extern MagickExport MagickPassFail AnimateImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), BenchmarkImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), CompareImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), CompositeImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), ConjureImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), ConvertImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), DisplayImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), IdentifyImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), ImportImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), MagickCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), MogrifyImage(const ImageInfo *,int,char **,Image **), MogrifyImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), MogrifyImages(const ImageInfo *,int,char **,Image **), MontageImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception), TimeImageCommand(ImageInfo *image_info,int argc,char **argv, char **metadata,ExceptionInfo *exception); extern MagickExport int GMCommand(int argc,char **argv); #if defined(MAGICK_IMPLEMENTATION) # include "magick/command-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/common.h ================================================ /* Copyright (C) 2009-2016 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Magick API common definitions support. */ #ifndef _MAGICK_COMMON_H #define _MAGICK_COMMON_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* * Borland C++ Builder DLL compilation defines */ #if defined(__BORLANDC__) && defined(_DLL) # pragma message("BCBMagick lib DLL export interface") # define _MAGICKDLL_ # define _MAGICKLIB_ # undef BuildMagickModules # define SupportMagickModules #endif #if defined(MSWINDOWS) && !defined(__CYGWIN__) # if defined(_MT) && defined(_DLL) && !defined(_MAGICKDLL_) && !defined(_LIB) # define _MAGICKDLL_ # endif # if defined(_MAGICKDLL_) # if defined(_VISUALC_) # pragma warning( disable: 4273 ) /* Disable the dll linkage warnings */ # endif # if !defined(_MAGICKLIB_) # define MagickExport __declspec(dllimport) # if defined(_VISUALC_) # pragma message( "Magick lib DLL import interface" ) # endif # else # define MagickExport __declspec(dllexport) # if defined(_VISUALC_) # pragma message( "Magick lib DLL export interface" ) # endif # endif # else # define MagickExport # if defined(_VISUALC_) # pragma message( "Magick lib static interface" ) # endif # endif # if defined(_DLL) && !defined(_LIB) # define ModuleExport __declspec(dllexport) # if defined(_VISUALC_) # pragma message( "Magick module DLL export interface" ) # endif # else # define ModuleExport # if defined(_VISUALC_) # pragma message( "Magick module static interface" ) # endif # endif # define MagickGlobal __declspec(thread) # if defined(_VISUALC_) # pragma warning(disable : 4018) # pragma warning(disable : 4244) # pragma warning(disable : 4244) # pragma warning(disable : 4275) /* non dll-interface class 'foo' used as base for dll-interface class 'bar' */ # pragma warning(disable : 4800) # pragma warning(disable : 4786) # pragma warning(disable : 4996) /* function deprecation warnings */ # endif #else # define MagickExport # define ModuleExport # define MagickGlobal #endif /* This size is the default minimum string allocation size (heap or stack) for a C string in GraphicsMagick. The weird size is claimed to be based on 2*FILENAME_MAX (not including terminating NULL) on some antique system. Linux has a FILENAME_MAX definition, but it is 4096 bytes. Many OSs have path limits of 1024 bytes. The FormatString() function assumes that the buffer it is writing to has at least this many bytes remaining. */ #if !defined(MaxTextExtent) # define MaxTextExtent 2053 #endif #define MagickSignature 0xabacadabUL #define MagickPassFail unsigned int #define MagickPass 1 #define MagickFail 0 #define MagickBool unsigned int #define MagickTrue 1 #define MagickFalse 0 /* Support for __attribute__ was added in GCC 2.0. It is not supported in strict ANSI mode which is indicated by __STRICT_ANSI__ being defined. http://www.ohse.de/uwe/articles/gcc-attributes.html Note that GCC 3.2 on MinGW does not define __GNUC__ or __GNUC_MINOR__. Clang/llvm and GCC 5.0 support __has_attribute(attribute) to test if an attribute is supported. Clang/llvm supports __has_builtin(builtin) to test if a builtin is supported. Clang/llvm attempts to support most GCC features. __SANITIZE_ADDRESS__ is defined by GCC and Clang if -fsanitize=address is supplied. After incuding valgrind/memcheck.h or valgrind/valgrind.h, the macro RUNNING_ON_VALGRIND can be used to test if the program is run under valgrind. See http://valgrind.org/docs/manual/manual-core-adv.html. */ #if !defined(MAGICK_ATTRIBUTE) # if ((!defined(__clang__)) && (!defined(__GNUC__) || (__GNUC__ < 2 || __STRICT_ANSI__))) # define MAGICK_ATTRIBUTE(x) /*nothing*/ # else # define MAGICK_ATTRIBUTE(x) __attribute__(x) # if ((defined(__clang__) || (defined(__GNUC__) && __GNUC__ >= 5)) && !defined(__COVERITY__)) # define MAGICK_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) # else # define MAGICK_HAS_ATTRIBUTE(attribute) (0) # endif # if (defined(__clang__) && !defined(__COVERITY__)) # define MAGICK_CLANG_HAS_BUILTIN(builtin) __has_builtin(builtin) # else # define MAGICK_CLANG_HAS_BUILTIN(builtin) (0) # endif # if ((MAGICK_HAS_ATTRIBUTE(__deprecated__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))) /* 3.1+ */ # define MAGICK_FUNC_DEPRECATED MAGICK_ATTRIBUTE((__deprecated__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__malloc__)) || \ (__GNUC__ >= 3)) /* 3.0+ */ # define MAGICK_FUNC_MALLOC MAGICK_ATTRIBUTE((__malloc__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__nonnull__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)))) /* 3.3+ */ /* Supports argument syntax like MAGICK_ATTRIBUTE((nonnull (1, 2))) but don't know how to support non-GCC fallback. */ # define MAGICK_FUNC_NONNULL MAGICK_ATTRIBUTE((__nonnull__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__noreturn__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 5)))) /* 2.5+ */ # define MAGICK_FUNC_NORETURN MAGICK_ATTRIBUTE((__noreturn__)) # endif /* clang 3.0 seems to have difficulties with __has_attribute(__const__) but clang 3.3 does not. Just assume that it is supported for clang since Linux headers are riddled with it. */ # if (defined(__clang__) || \ (((__GNUC__) > 3) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 5)))) /* 2.5+ */ # define MAGICK_FUNC_CONST MAGICK_ATTRIBUTE((__const__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__pure__)) || \ ((__GNUC__) >= 3)) /* 2.96+ */ # define MAGICK_FUNC_PURE MAGICK_ATTRIBUTE((__pure__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__unused__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 7)))) /* 2.7+ */ # define MAGICK_FUNC_UNUSED MAGICK_ATTRIBUTE((__unused__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__warn_unused_result__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)))) /* 3.3+ */ # define MAGICK_FUNC_WARN_UNUSED_RESULT MAGICK_ATTRIBUTE((__warn_unused_result__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__noinline__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))) /* 3.4+ */ # define MAGICK_FUNC_NOINLINE MAGICK_ATTRIBUTE((__noinline__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__always_inline__)) || \ (((__GNUC__) > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))) /* 3.4+ */ # define MAGICK_FUNC_ALWAYSINLINE MAGICK_ATTRIBUTE((__always_inline__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__alloc_size__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) /* 4.3+ */ # define MAGICK_FUNC_ALLOC_SIZE_1ARG(arg_num) MAGICK_ATTRIBUTE((__alloc_size__(arg_num))) # define MAGICK_FUNC_ALLOC_SIZE_2ARG(arg_num1,arg_num2) MAGICK_ATTRIBUTE((__alloc_size__(arg_num1,arg_num2))) # endif # if ((MAGICK_HAS_ATTRIBUTE(__hot__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) /* 4.3+ */ # define MAGICK_FUNC_HOT MAGICK_ATTRIBUTE((__hot__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__cold__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) /* 4.3+ */ # define MAGICK_FUNC_COLD MAGICK_ATTRIBUTE((__cold__)) # endif # if ((MAGICK_HAS_ATTRIBUTE(__optimize__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) /* 4.3+ */ # define MAGICK_OPTIMIZE_FUNC(opt) MAGICK_ATTRIBUTE((__optimize__ (opt))) # endif /* GCC 7 and later support a fallthrough attribute to mark switch statement cases which are intended to fall through. Clang 3.5.0 supports a clang::fallthrough statement attribute while Clang 10 supports the same attribute as GCC 7. Some compilers support a FALLTHROUGH (or FALLTHRU) pre-processor comment. C++ 17 supports a standard fallthrough attribute of the form "[[fallthrough]]". See https://developers.redhat.com/blog/2017/03/10/wimplicit-fallthrough-in-gcc-7/, https://gcc.gnu.org/onlinedocs/gcc/Statement-Attributes.html, https://clang.llvm.org/docs/AttributeReference.html#fallthrough, and https://releases.llvm.org/3.7.0/tools/clang/docs/AttributeReference.html#fallthrough-clang-fallthrough Usage is to put "MAGICK_FALLTHROUGH;" where a "break;" would go. */ # if ((MAGICK_HAS_ATTRIBUTE(__fallthrough__)) || \ ((__GNUC__) >= 7)) /* 7+ */ # define MAGICK_FALLTHROUGH MAGICK_ATTRIBUTE((__fallthrough__)) # endif /* https://code.google.com/p/address-sanitizer/wiki/AddressSanitizer#Introduction To ignore certain functions, one can use the no_sanitize_address attribute supported by Clang (3.3+) and GCC (4.8+). */ # if ((MAGICK_HAS_ATTRIBUTE(__no_sanitize_address__)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 8) && (__GNUC_MINOR__ >= 0)))) /* 4.8+ */ # define MAGICK_NO_SANITIZE_ADDRESS MAGICK_ATTRIBUTE((__no_sanitize_address__)) # endif # if ((MAGICK_CLANG_HAS_BUILTIN(__builtin_assume_aligned)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)))) /* 4.7+ */ # define MAGICK_ASSUME_ALIGNED(exp,align) __builtin_assume_aligned(exp,align) # endif # if ((MAGICK_CLANG_HAS_BUILTIN(__builtin_assume_aligned)) || \ (((__GNUC__) > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)))) /* 4.7+ */ # define MAGICK_ASSUME_ALIGNED_OFFSET(exp,align,offset) __builtin_assume_aligned(exp,align,offset) # endif # endif #endif #if !defined(MAGICK_FUNC_DEPRECATED) # define MAGICK_FUNC_DEPRECATED /*nothing*/ #endif #if !defined(MAGICK_FUNC_MALLOC) # define MAGICK_FUNC_MALLOC /*nothing*/ #endif #if !defined (MAGICK_FUNC_NONNULL) # define MAGICK_FUNC_NONNULL /*nothing*/ #endif #if !defined (MAGICK_FUNC_NORETURN) # define MAGICK_FUNC_NORETURN /*nothing*/ #endif #if !defined (MAGICK_FUNC_CONST) # define MAGICK_FUNC_CONST /*nothing*/ #endif #if !defined (MAGICK_FUNC_PURE) # define MAGICK_FUNC_PURE /*nothing*/ #endif #if !defined (MAGICK_FUNC_UNUSED) # define MAGICK_FUNC_UNUSED /*nothing*/ #endif #if !defined(MAGICK_FUNC_WARN_UNUSED_RESULT) # define MAGICK_FUNC_WARN_UNUSED_RESULT /*nothing*/ #endif #if !defined(MAGICK_FUNC_NOINLINE) # define MAGICK_FUNC_NOINLINE /*nothing*/ #endif #if !defined(MAGICK_FUNC_ALWAYSINLINE) # define MAGICK_FUNC_ALWAYSINLINE /*nothing*/ #endif #if !defined(MAGICK_FUNC_ALLOC_SIZE_1ARG) # define MAGICK_FUNC_ALLOC_SIZE_1ARG(arg_num) /*nothing*/ #endif #if !defined(MAGICK_FUNC_ALLOC_SIZE_2ARG) # define MAGICK_FUNC_ALLOC_SIZE_2ARG(arg_num1,arg_num2) /*nothing*/ #endif #if !defined(MAGICK_FUNC_HOT) # define MAGICK_FUNC_HOT /*nothing*/ #endif #if !defined(MAGICK_FUNC_COLD) # define MAGICK_FUNC_COLD /*nothing*/ #endif #if !defined(MAGICK_OPTIMIZE_FUNC) # define MAGICK_OPTIMIZE_FUNC(opt) /*nothing*/ #endif #if !defined(MAGICK_FALLTHROUGH) # define MAGICK_FALLTHROUGH /*nothing*/ #endif #if !defined(MAGICK_ASSUME_ALIGNED) # define MAGICK_ASSUME_ALIGNED(exp,align) (exp) #endif #if !defined(MAGICK_ASSUME_ALIGNED_OFFSET) # define MAGICK_ASSUME_ALIGNED_OFFSET(exp,align,offset) (exp) #endif /* The isnan and isinf macros are defined by c99 but might not always be available. If they (or a substitute) are not available, then define them to a false value. */ #if defined(isnan) #define MAGICK_ISNAN(d) isnan(d) #else #define MAGICK_ISNAN(d) (0) #endif #if defined(isinf) #define MAGICK_ISINF(d) isinf(d) #else #define MAGICK_ISINF(d) (0) #endif #if defined(isnormal) #define MAGICK_ISNORMAL(d) isnormal(d) #else #define MAGICK_ISNORMAL(d) (1) #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_COMMON_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/compare.h ================================================ /* Copyright (C) 2008 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Comparison Methods. */ #ifndef _MAGICK_COMPARE_H #define _MAGICK_COMPARE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Pixel differencing algorithms. */ typedef enum { UndefinedHighlightStyle, AssignHighlightStyle, ThresholdHighlightStyle, TintHighlightStyle, XorHighlightStyle } HighlightStyle; typedef struct _DifferenceImageOptions { ChannelType channel; /* Channel(s) to difference */ HighlightStyle highlight_style; /* Pixel annotation style */ PixelPacket highlight_color; /* Changed pixel highlight color */ } DifferenceImageOptions; extern MagickExport void InitializeDifferenceImageOptions(DifferenceImageOptions *options, ExceptionInfo *exception); extern MagickExport Image *DifferenceImage(const Image *reference_image,const Image *compare_image, const DifferenceImageOptions *difference_options, ExceptionInfo *exception); /* Pixel error metrics. */ typedef enum { UndefinedMetric, MeanAbsoluteErrorMetric, MeanSquaredErrorMetric, PeakAbsoluteErrorMetric, PeakSignalToNoiseRatioMetric, RootMeanSquaredErrorMetric } MetricType; /* Pixel difference statistics. */ typedef struct _DifferenceStatistics { double red, green, blue, opacity, combined; } DifferenceStatistics; extern MagickExport void InitializeDifferenceStatistics(DifferenceStatistics *difference_statistics, ExceptionInfo *exception); extern MagickExport MagickPassFail GetImageChannelDifference(const Image *reference_image, const Image *compare_image, const MetricType metric, DifferenceStatistics *statistics, ExceptionInfo *exception), GetImageChannelDistortion(const Image *reference_image, const Image *compare_image, const ChannelType channel, const MetricType metric, double *distortion, ExceptionInfo *exception), GetImageDistortion(const Image *reference_image, const Image *compare_image, const MetricType metric, double *distortion, ExceptionInfo *exception); extern MagickExport MagickBool IsImagesEqual(Image *,const Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_COMPARE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/composite.h ================================================ /* Copyright (C) 2003 - 2010 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Composite Methods. */ #ifndef _MAGICK_COMPOSITE_H #define _MAGICK_COMPOSITE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Special options required by some composition operators. */ typedef struct _CompositeOptions_t { /* ModulateComposite */ double percent_brightness; /* ThresholdComposite */ double amount; double threshold; } CompositeOptions_t; extern MagickExport MagickPassFail CompositeImage(Image *canvas_image,const CompositeOperator compose, const Image *update_image, const long x_offset,const long y_offset), CompositeImageRegion(const CompositeOperator compose, const CompositeOptions_t *options, const unsigned long columns, const unsigned long rows, const Image *update_image, const long update_x, const long update_y, Image *canvas_image, const long canvas_x, const long canvas_y, ExceptionInfo *exception), MagickCompositeImageUnderColor(Image *image,const PixelPacket *undercolor, ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_COMPOSITE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/compress.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Image Compression/Decompression Methods. */ #ifndef _MAGICK_COMPRESS_H #define _MAGICK_COMPRESS_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Typedef declaration. */ typedef struct _Ascii85Info { long offset, line_break; magick_uint8_t buffer[10]; } Ascii85Info; /* TODO: Clean up the interface between BLOB write functions, compression functions, and encoding functions so they may be hooked into/stacked on top of each other. Most are (or can be changed to be) stream based. */ typedef unsigned int (*WriteByteHook)(Image *, const magick_uint8_t, void *info); /* Commonly used byte writer hooks. */ extern MagickExport unsigned int Ascii85WriteByteHook(Image *image, const magick_uint8_t code, void *info), BlobWriteByteHook(Image *image, const magick_uint8_t code, void *info); /* Compress methods. */ extern MagickExport MagickPassFail HuffmanDecodeImage(Image *image), HuffmanEncodeImage(const ImageInfo *image_info,Image *image), HuffmanEncode2Image(const ImageInfo *image_info,Image *image,WriteByteHook write_byte,void *info), LZWEncodeImage(Image *image,const size_t length,magick_uint8_t *pixels), LZWEncode2Image(Image *image,const size_t length,magick_uint8_t *pixels,WriteByteHook write_byte,void *info), PackbitsEncodeImage(Image *image,const size_t length,magick_uint8_t *pixels), PackbitsEncode2Image(Image *image,const size_t length,magick_uint8_t *pixels,WriteByteHook write_byte,void *info); extern MagickExport unsigned char *ImageToHuffman2DBlob(const Image *image,const ImageInfo *image_info, size_t *length,ExceptionInfo *exception), *ImageToJPEGBlob(const Image *image,const ImageInfo *image_info, size_t *length,ExceptionInfo *exception); extern MagickExport void Ascii85Encode(Image *image,const magick_uint8_t code), Ascii85Flush(Image *image), Ascii85Initialize(Image *image); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/confirm_access.h ================================================ /* Copyright (C) 2009 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Access Confirmation Methods. */ #ifndef _MAGICK_CONFIRM_ACCESS_H #define _MAGICK_CONFIRM_ACCESS_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif typedef enum { UndefinedConfirmAccessMode, FileExecuteConfirmAccessMode, /* Path is to be opened for execution */ FileReadConfirmAccessMode, /* Path is to be opened for read */ FileWriteConfirmAccessMode, /* Path is to be opened for write */ URLGetFTPConfirmAccessMode, /* ftp:// URL get */ URLGetFileConfirmAccessMode, /* file:// URL get */ URLGetHTTPConfirmAccessMode /* http:// URL get */ } ConfirmAccessMode; typedef MagickPassFail (*ConfirmAccessHandler)(const ConfirmAccessMode mode, const char *path, ExceptionInfo *exception); extern MagickExport MagickPassFail MagickConfirmAccess(const ConfirmAccessMode mode, const char *path, ExceptionInfo *exception); extern MagickExport ConfirmAccessHandler MagickSetConfirmAccessHandler(ConfirmAccessHandler handler); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_CONFIRM_ACCESS_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/constitute.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Constitute Methods. */ #ifndef _MAGICK_CONSTITUTE_H #define _MAGICK_CONSTITUTE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Quantum import/export types as used by ImportImagePixelArea() and ExportImagePixelArea(). Values are imported or exported in network byte order ("big endian") by default, but little endian may be selected via the 'endian' option in ExportPixelAreaOptions and ImportPixelAreaOptions. */ typedef enum { UndefinedQuantum, /* Not specified */ IndexQuantum, /* Colormap indexes */ GrayQuantum, /* Grayscale values (minimum value is black) */ IndexAlphaQuantum, /* Colormap indexes with transparency */ GrayAlphaQuantum, /* Grayscale values with transparency */ RedQuantum, /* Red values only (RGBA) */ CyanQuantum, /* Cyan values only (CMYKA) */ GreenQuantum, /* Green values only (RGBA) */ YellowQuantum, /* Yellow values only (CMYKA) */ BlueQuantum, /* Blue values only (RGBA) */ MagentaQuantum, /* Magenta values only (CMYKA) */ AlphaQuantum, /* Transparency values (RGBA or CMYKA) */ BlackQuantum, /* Black values only (CMYKA) */ RGBQuantum, /* Red, green, and blue values */ RGBAQuantum, /* Red, green, blue, and transparency values */ CMYKQuantum, /* Cyan, magenta, yellow, and black values */ CMYKAQuantum, /* Cyan, magenta, yellow, black, and transparency values */ CIEYQuantum, /* CIE Y values, based on CCIR-709 primaries */ CIEXYZQuantum /* CIE XYZ values, based on CCIR-709 primaries */ } QuantumType; /* Quantum sample type for when exporting/importing a pixel area. */ typedef enum { UndefinedQuantumSampleType, /* Not specified */ UnsignedQuantumSampleType, /* Unsigned integral type (1-32 or 64 bits) */ FloatQuantumSampleType /* Floating point type (16, 24, 32, or 64 bit) */ } QuantumSampleType; /* Quantum size types as used by ConstituteImage() and DispatchImage()/ */ typedef enum { CharPixel, /* Unsigned 8 bit 'unsigned char' */ ShortPixel, /* Unsigned 16 bit 'unsigned short int' */ IntegerPixel, /* Unsigned 32 bit 'unsigned int' */ LongPixel, /* Unsigned 32 or 64 bit (CPU dependent) 'unsigned long' */ FloatPixel, /* Floating point 32-bit 'float' */ DoublePixel /* Floating point 64-bit 'double' */ } StorageType; /* Additional options for ExportImagePixelArea() */ typedef struct _ExportPixelAreaOptions { QuantumSampleType sample_type; /* Quantum sample type */ double double_minvalue, /* Minimum value (default 0.0) for linear floating point samples */ double_maxvalue; /* Maximum value (default 1.0) for linear floating point samples */ MagickBool grayscale_miniswhite; /* Grayscale minimum value is white rather than black */ unsigned long pad_bytes; /* Number of pad bytes to output after pixel data */ unsigned char pad_value; /* Value to use when padding end of pixel data */ EndianType endian; /* Endian orientation for 16/32/64 bit types (default MSBEndian) */ unsigned long signature; } ExportPixelAreaOptions; /* Optional results info for ExportImagePixelArea() */ typedef struct _ExportPixelAreaInfo { size_t bytes_exported; /* Number of bytes which were exported */ } ExportPixelAreaInfo; /* Additional options for ImportImagePixelArea() */ typedef struct _ImportPixelAreaOptions { QuantumSampleType sample_type; /* Quantum sample type */ double double_minvalue, /* Minimum value (default 0.0) for linear floating point samples */ double_maxvalue; /* Maximum value (default 1.0) for linear floating point samples */ MagickBool grayscale_miniswhite; /* Grayscale minimum value is white rather than black */ EndianType endian; /* Endian orientation for 16/32/64 bit types (default MSBEndian) */ unsigned long signature; } ImportPixelAreaOptions; /* Optional results info for ImportImagePixelArea() */ typedef struct _ImportPixelAreaInfo { size_t bytes_imported; /* Number of bytes which were imported */ } ImportPixelAreaInfo; extern MagickExport const char *StorageTypeToString(const StorageType storage_type), *QuantumSampleTypeToString(const QuantumSampleType sample_type), *QuantumTypeToString(const QuantumType quantum_type); extern MagickExport Image *ConstituteImage(const unsigned long width,const unsigned long height, const char *map,const StorageType type,const void *pixels, ExceptionInfo *exception), *ConstituteTextureImage(const unsigned long columns,const unsigned long rows, const Image *texture,ExceptionInfo *exception), *PingImage(const ImageInfo *image_info,ExceptionInfo *exception), *ReadImage(const ImageInfo *image_info,ExceptionInfo *exception), *ReadInlineImage(const ImageInfo *image_info,const char *content, ExceptionInfo *exception); extern MagickExport MagickPassFail DispatchImage(const Image *image,const long x_offset,const long y_offset, const unsigned long columns,const unsigned long rows,const char *map, const StorageType type,void *pixels,ExceptionInfo *exception), ExportImagePixelArea(const Image *image,const QuantumType quantum_type, const unsigned int quantum_size,unsigned char *destination, const ExportPixelAreaOptions *options,ExportPixelAreaInfo *export_info), ExportViewPixelArea(const ViewInfo *view,const QuantumType quantum_type, const unsigned int quantum_size,unsigned char *destination, const ExportPixelAreaOptions *options,ExportPixelAreaInfo *export_info); extern MagickExport MagickPassFail ImportImagePixelArea(Image *image,const QuantumType quantum_type, const unsigned int quantum_size,const unsigned char *source, const ImportPixelAreaOptions *options,ImportPixelAreaInfo *import_info), ImportViewPixelArea(ViewInfo *view,const QuantumType quantum_type, const unsigned int quantum_size,const unsigned char *source, const ImportPixelAreaOptions *options,ImportPixelAreaInfo *import_info), WriteImage(const ImageInfo *image_info,Image *image), WriteImages(const ImageInfo *image_info,Image *image,const char *filename, ExceptionInfo *exception), WriteImagesFile(const ImageInfo *image_info,Image *image,FILE * file, ExceptionInfo *exception); extern MagickExport void ExportPixelAreaOptionsInit(ExportPixelAreaOptions *options), ImportPixelAreaOptionsInit(ImportPixelAreaOptions *options); extern MagickExport MagickPassFail MagickFindRawImageMinMax(Image *image, EndianType endian, unsigned long width, unsigned long height,StorageType type, unsigned scanline_octets, void *scanline_buffer, double *min, double *max); extern MagickExport unsigned int MagickGetQuantumSamplesPerPixel(const QuantumType quantum_type) MAGICK_FUNC_CONST; #if defined(MAGICK_IMPLEMENTATION) # include "magick/constitute-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_CONSTITUTE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/decorate.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Decorate Methods. */ #ifndef _MAGICK_DECORATE_H #define _MAGICK_DECORATE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *BorderImage(const Image *,const RectangleInfo *,ExceptionInfo *), *FrameImage(const Image *,const FrameInfo *,ExceptionInfo *); MagickExport unsigned int RaiseImage(Image *,const RectangleInfo *,const int); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_DECORATE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/delegate.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Methods to Read/Write/Invoke Delegates. */ #ifndef _MAGICK_DELEGATE_H #define _MAGICK_DELEGATE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Delegate structure definitions. */ typedef struct _DelegateInfo { char *path, /* Path to delegate configuation file */ *decode, /* Decode from format */ *encode; /* Transcode to format */ char *commands; /* Commands to execute */ int mode; /* <0 = encoder, >0 = decoder */ MagickBool stealth; /* Don't list this delegate */ unsigned long signature; struct _DelegateInfo *previous, *next; } DelegateInfo; /* Magick delegate methods. */ extern MagickExport char *GetDelegateCommand(const ImageInfo *image_info,Image *image, const char *decode,const char *encode, ExceptionInfo *exception); extern MagickExport const DelegateInfo *GetDelegateInfo(const char *decode,const char *encode, ExceptionInfo *exception), *GetPostscriptDelegateInfo(const ImageInfo *image_info, unsigned int *antialias, ExceptionInfo *exception); extern MagickExport DelegateInfo *SetDelegateInfo(DelegateInfo *); extern MagickExport MagickPassFail InvokePostscriptDelegate(const unsigned int verbose,const char *command, ExceptionInfo *exception), InvokeDelegate(ImageInfo *image_info,Image *image,const char *decode, const char *encode,ExceptionInfo *exception), ListDelegateInfo(FILE *file,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) #if defined(HasGS) #include "ghostscript/iapi.h" #endif #ifndef gs_main_instance_DEFINED # define gs_main_instance_DEFINED typedef struct gs_main_instance_s gs_main_instance; #endif #if !defined(MagickDLLCall) # if defined(MSWINDOWS) # define MagickDLLCall __stdcall # else # define MagickDLLCall # endif #endif /* Define a vector of Ghostscript library callback functions so that DLL/shared and static Ghostscript libbraries may be handled identically. These definitions must be compatible with those in the Ghostscript API headers (which we don't require). http://pages.cs.wisc.edu/~ghost/doc/cvs/API.htm */ typedef struct _GhostscriptVectors { /* Exit the interpreter (gsapi_exit)*/ int (MagickDLLCall *exit)(gs_main_instance *instance); /* Destroy instance of Ghostscript. Call exit first! (gsapi_delete_instance) */ void (MagickDLLCall *delete_instance)(gs_main_instance *instance); /* Initialize the Ghostscript interpreter (gsapi_init_with_args) */ int (MagickDLLCall *init_with_args)(gs_main_instance *instance,int argc, char **argv); /* Create a new instance of the Ghostscript interpreter (gsapi_new_instance) */ int (MagickDLLCall *new_instance)(gs_main_instance **pinstance, void *caller_handle); /* Execute string command in Ghostscript interpreter (gsapi_run_string) */ int (MagickDLLCall *run_string)(gs_main_instance *instance,const char *str, int user_errors,int *pexit_code); } GhostscriptVectors; extern MagickExport void DestroyDelegateInfo(void); extern MagickPassFail InitializeDelegateInfo(void); #endif /* MAGICK_IMPLEMENTATION */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_DELEGATE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/deprecate.h ================================================ /* Copyright (C) 2003, 2008 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Log methods. */ #ifndef _MAGICK_DEPRECATE_H #define _MAGICK_DEPRECATE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Legacy names for (possibly) large integral types */ #if !defined(ExtendedSignedIntegralType) # define ExtendedSignedIntegralType magick_int64_t #endif #if !defined(ExtendedUnsignedIntegralType) # define ExtendedUnsignedIntegralType magick_uint64_t #endif /* Compatibility definitions to handle the renaming of ExtendedSignedIntegralType and ExtendedUnsignedIntegralType to MagickSignedType and MagickUnsignedType which occured in ImageMagick 5.5.8. ImageMagick 5.5.8 also introduced MagickRationalType. */ #if !defined(MagickSignedType) # define MagickSignedType magick_int64_t #endif #if !defined(MagickUnsignedType) # define MagickUnsignedType magick_uint64_t #endif #if !defined(MagickRationalType) # if defined(HAVE_LONG_DOUBLE) # define MagickRationalType long double # else # define MagickRationalType double # endif #endif extern MagickExport unsigned int PopImagePixels(const Image *,const QuantumType,unsigned char *) MAGICK_FUNC_DEPRECATED; extern MagickExport unsigned int PushImagePixels(Image *,const QuantumType,const unsigned char *) MAGICK_FUNC_DEPRECATED; extern MagickExport void *AcquireMemory(const size_t) MAGICK_FUNC_DEPRECATED MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(1); extern MagickExport void *CloneMemory(void *,const void *,const size_t) MAGICK_FUNC_DEPRECATED; extern MagickExport void LiberateMemory(void **) MAGICK_FUNC_DEPRECATED; extern MagickExport void ReacquireMemory(void **,const size_t) MAGICK_FUNC_DEPRECATED; extern MagickExport const PixelPacket *AcquireCacheView(ViewInfo *view, const long x,const long y,const unsigned long columns, const unsigned long rows,ExceptionInfo *exception) MAGICK_FUNC_DEPRECATED; extern MagickExport PixelPacket *GetCacheView(ViewInfo *view,const long x,const long y, const unsigned long columns,const unsigned long rows) MAGICK_FUNC_DEPRECATED; extern MagickExport PixelPacket *SetCacheView(ViewInfo *view,const long x,const long y, const unsigned long columns,const unsigned long rows) MAGICK_FUNC_DEPRECATED; extern MagickExport MagickPassFail SyncCacheView(ViewInfo *view) MAGICK_FUNC_DEPRECATED; #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/describe.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Describe Methods. */ #ifndef _MAGICK_DESCRIBE_H #define _MAGICK_DESCRIBE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" extern MagickExport MagickPassFail DescribeImage(Image *image,FILE *file,const MagickBool verbose); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_DESCRIBE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/draw.h ================================================ /* Copyright (C) 2003-2018 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Drawing API. Usage synopsis: DrawContext context; context = DrawAllocateContext((DrawInfo*)NULL, image); [ any number of drawing commands ] DrawSetStrokeColorString(context,"black"); DrawSetFillColorString(context,"#ff00ff"); DrawSetStrokeWidth(context,4); DrawRectangle(context,72,72,144,144); DrawRender(context); DrawDestroyContext(context); */ #ifndef _MAGICK_DRAW_H #define _MAGICK_DRAW_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/render.h" typedef struct _DrawContext *DrawContext; extern MagickExport ClipPathUnits DrawGetClipUnits(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport DrawInfo *DrawPeekGraphicContext(const DrawContext context); extern MagickExport DecorationType DrawGetTextDecoration(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport DrawContext DrawAllocateContext(const DrawInfo *draw_info, Image *image); extern MagickExport FillRule DrawGetClipRule(DrawContext context) MAGICK_FUNC_PURE, DrawGetFillRule(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport GravityType DrawGetGravity(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport LineCap DrawGetStrokeLineCap(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport LineJoin DrawGetStrokeLineJoin(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport PixelPacket DrawGetFillColor(DrawContext context) MAGICK_FUNC_PURE, DrawGetStrokeColor(DrawContext context) MAGICK_FUNC_PURE, DrawGetTextUnderColor(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport StretchType DrawGetFontStretch(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport StyleType DrawGetFontStyle(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport char *DrawGetClipPath(DrawContext context), *DrawGetFont(DrawContext context), *DrawGetFontFamily(DrawContext context), *DrawGetTextEncoding(DrawContext context); extern MagickExport int DrawRender(const DrawContext context); extern MagickExport unsigned int DrawGetStrokeAntialias(DrawContext context) MAGICK_FUNC_PURE, DrawGetTextAntialias(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport unsigned long DrawGetFontWeight(DrawContext context) MAGICK_FUNC_PURE, DrawGetStrokeMiterLimit(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport double DrawGetFillOpacity(DrawContext context) MAGICK_FUNC_PURE, DrawGetFontSize(DrawContext context) MAGICK_FUNC_PURE, *DrawGetStrokeDashArray(DrawContext context, unsigned long *num_elems), DrawGetStrokeDashOffset(DrawContext context) MAGICK_FUNC_PURE, DrawGetStrokeOpacity(DrawContext context) MAGICK_FUNC_PURE, DrawGetStrokeWidth(DrawContext context) MAGICK_FUNC_PURE; extern MagickExport void DrawAffine(DrawContext context, const AffineMatrix *affine), DrawAnnotation(DrawContext context, const double x, const double y, const unsigned char *text), DrawArc(DrawContext context, const double sx, const double sy, const double ex, const double ey, const double sd, const double ed), DrawBezier(DrawContext context, const unsigned long num_coords, const PointInfo * coordinates), DrawCircle(DrawContext context, const double ox, const double oy, const double px, const double py), DrawColor(DrawContext context, const double x, const double y, const PaintMethod paintMethod), DrawComment(DrawContext context,const char* comment), DrawDestroyContext(DrawContext context), DrawEllipse(DrawContext context, const double ox, const double oy, const double rx, const double ry, const double start, const double end), DrawComposite(DrawContext context, const CompositeOperator composite_operator, const double x, const double y, const double width, const double height, const Image * image ), DrawLine(DrawContext context, const double sx, const double sy, const double ex, const double ey), DrawMatte(DrawContext context, const double x, const double y, const PaintMethod paint_method), DrawPathClose(DrawContext context), DrawPathCurveToAbsolute(DrawContext context, const double x1, const double y1, const double x2, const double y2, const double x, const double y), DrawPathCurveToRelative(DrawContext context, const double x1, const double y1, const double x2, const double y2, const double x, const double y), DrawPathCurveToQuadraticBezierAbsolute(DrawContext context, const double x1, const double y1, const double x, const double y), DrawPathCurveToQuadraticBezierRelative(DrawContext context, const double x1, const double y1, const double x, const double y), DrawPathCurveToQuadraticBezierSmoothAbsolute(DrawContext context, const double x, const double y), DrawPathCurveToQuadraticBezierSmoothRelative(DrawContext context, const double x, const double y), DrawPathCurveToSmoothAbsolute(DrawContext context, const double x2, const double y2, const double x, const double y), DrawPathCurveToSmoothRelative(DrawContext context, const double x2, const double y2, const double x, const double y), DrawPathEllipticArcAbsolute(DrawContext context, const double rx, const double ry, const double x_axis_rotation, unsigned int large_arc_flag, unsigned int sweep_flag, const double x, const double y), DrawPathEllipticArcRelative(DrawContext context, const double rx, const double ry, const double x_axis_rotation, unsigned int large_arc_flag, unsigned int sweep_flag, const double x, const double y), DrawPathFinish(DrawContext context), DrawPathLineToAbsolute(DrawContext context, const double x, const double y), DrawPathLineToRelative(DrawContext context, const double x, const double y), DrawPathLineToHorizontalAbsolute(DrawContext context, const double x), DrawPathLineToHorizontalRelative(DrawContext context, const double x), DrawPathLineToVerticalAbsolute(DrawContext context, const double y), DrawPathLineToVerticalRelative(DrawContext context, const double y), DrawPathMoveToAbsolute(DrawContext context, const double x, const double y), DrawPathMoveToRelative(DrawContext context, const double x, const double y), DrawPathStart(DrawContext context), DrawPoint(DrawContext context, const double x, const double y), DrawPolygon(DrawContext context, const unsigned long num_coords, const PointInfo * coordinates), DrawPolyline(DrawContext context, const unsigned long num_coords, const PointInfo * coordinates), DrawPopClipPath(DrawContext context), DrawPopDefs(DrawContext context), DrawPopGraphicContext(DrawContext context), DrawPopPattern(DrawContext context), DrawPushClipPath(DrawContext context, const char *clip_path_id), DrawPushDefs(DrawContext context), DrawPushGraphicContext(DrawContext context), DrawPushPattern(DrawContext context, const char *pattern_id, const double x, const double y, const double width, const double height), DrawRectangle(DrawContext context, const double x1, const double y1, const double x2, const double y2), DrawRoundRectangle(DrawContext context, double x1, double y1, double x2, double y2, double rx, double ry), DrawScale(DrawContext context, const double x, const double y), DrawSetClipPath(DrawContext context, const char *clip_path), DrawSetClipRule(DrawContext context, const FillRule fill_rule), DrawSetClipUnits(DrawContext context, const ClipPathUnits clip_units), DrawSetFillColor(DrawContext context, const PixelPacket *fill_color), DrawSetFillColorString(DrawContext context, const char *fill_color), DrawSetFillOpacity(DrawContext context, const double fill_opacity), DrawSetFillRule(DrawContext context, const FillRule fill_rule), DrawSetFillPatternURL(DrawContext context, const char *fill_url), DrawSetFont(DrawContext context, const char *font_name), DrawSetFontFamily(DrawContext context, const char *font_family), DrawSetFontSize(DrawContext context, const double font_pointsize), DrawSetFontStretch(DrawContext context, const StretchType font_stretch), DrawSetFontStyle(DrawContext context, const StyleType font_style), DrawSetFontWeight(DrawContext context, const unsigned long font_weight), DrawSetGravity(DrawContext context, const GravityType gravity), DrawRotate(DrawContext context, const double degrees), DrawSkewX(DrawContext context, const double degrees), DrawSkewY(DrawContext context, const double degrees), /* DrawSetStopColor(DrawContext context, const PixelPacket * color, const double offset), */ DrawSetStrokeAntialias(DrawContext context, const unsigned int true_false), DrawSetStrokeColor(DrawContext context, const PixelPacket *stroke_color), DrawSetStrokeColorString(DrawContext context, const char *stroke_color), DrawSetStrokeDashArray(DrawContext context, const unsigned long num_elems, const double *dasharray), DrawSetStrokeDashOffset(DrawContext context,const double dashoffset), DrawSetStrokeLineCap(DrawContext context, const LineCap linecap), DrawSetStrokeLineJoin(DrawContext context, const LineJoin linejoin), DrawSetStrokeMiterLimit(DrawContext context,const unsigned long miterlimit), DrawSetStrokeOpacity(DrawContext context, const double opacity), DrawSetStrokePatternURL(DrawContext context, const char* stroke_url), DrawSetStrokeWidth(DrawContext context, const double width), DrawSetTextAntialias(DrawContext context, const unsigned int true_false), DrawSetTextDecoration(DrawContext context, const DecorationType decoration), DrawSetTextEncoding(DrawContext context, const char *encoding), DrawSetTextUnderColor(DrawContext context, const PixelPacket *color), DrawSetTextUnderColorString(DrawContext context, const char *under_color), DrawSetViewbox(DrawContext context, unsigned long x1, unsigned long y1, unsigned long x2, unsigned long y2), DrawTranslate(DrawContext context, const double x, const double y); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/effect.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Effect Methods. */ #ifndef _MAGICK_EFFECT_H #define _MAGICK_EFFECT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *AdaptiveThresholdImage(const Image *,const unsigned long,const unsigned long, const double,ExceptionInfo *), *AddNoiseImage(const Image *,const NoiseType,ExceptionInfo *), *AddNoiseImageChannel(const Image *image,const ChannelType channel, const NoiseType noise_type,ExceptionInfo *exception), *BlurImage(const Image *,const double,const double,ExceptionInfo *), *BlurImageChannel(const Image *image,const ChannelType channel, const double radius,const double sigma,ExceptionInfo *exception), *ConvolveImage(const Image *,const unsigned int,const double *, ExceptionInfo *), *DespeckleImage(const Image *,ExceptionInfo *), *EdgeImage(const Image *,const double,ExceptionInfo *), *EmbossImage(const Image *,const double,const double,ExceptionInfo *), *EnhanceImage(const Image *,ExceptionInfo *), *GaussianBlurImage(const Image *,const double,const double,ExceptionInfo *), *GaussianBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception), *MedianFilterImage(const Image *,const double,ExceptionInfo *), *MotionBlurImage(const Image *,const double,const double,const double, ExceptionInfo *), *ReduceNoiseImage(const Image *,const double,ExceptionInfo *), *ShadeImage(const Image *,const unsigned int,double,double,ExceptionInfo *), *SharpenImage(const Image *,const double,const double,ExceptionInfo *), *SharpenImageChannel(const Image *image,const ChannelType channel, const double radius,const double sigma,ExceptionInfo *exception), *SpreadImage(const Image *,const unsigned int,ExceptionInfo *), *UnsharpMaskImage(const Image *,const double,const double,const double, const double,ExceptionInfo *), *UnsharpMaskImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, const double amount,const double threshold, ExceptionInfo *exception); extern MagickExport MagickPassFail BlackThresholdImage(Image *image,const char *thresholds), ChannelThresholdImage(Image *,const char *), RandomChannelThresholdImage(Image *,const char *,const char *, ExceptionInfo *exception), ThresholdImage(Image *,const double), WhiteThresholdImage(Image *image,const char *thresholds); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_EFFECT_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/enhance.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Enhancement Methods. */ #ifndef _MAGICK_ENHANCE_H #define _MAGICK_ENHANCE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport MagickPassFail ContrastImage(Image *,const unsigned int), EqualizeImage(Image *), GammaImage(Image *,const char *), LevelImage(Image *,const char *), LevelImageChannel(Image *,const ChannelType,const double,const double, const double), ModulateImage(Image *,const char *), NegateImage(Image *,const unsigned int), NormalizeImage(Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_ENHANCE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/error.h ================================================ /* Copyright (C) 2003-2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Exception Methods. */ #ifndef _MAGICK_ERROR_H #define _MAGICK_ERROR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Enum declarations. */ typedef enum { UndefinedExceptionBase = 0, ExceptionBase = 1, ResourceBase = 2, ResourceLimitBase = 2, TypeBase = 5, AnnotateBase = 5, OptionBase = 10, DelegateBase = 15, MissingDelegateBase = 20, CorruptImageBase = 25, FileOpenBase = 30, BlobBase = 35, StreamBase = 40, CacheBase = 45, CoderBase = 50, ModuleBase = 55, DrawBase = 60, RenderBase = 60, ImageBase = 65, WandBase = 67, TemporaryFileBase = 70, TransformBase = 75, XServerBase = 80, X11Base = 81, UserBase = 82, MonitorBase = 85, LocaleBase = 86, DeprecateBase = 87, RegistryBase = 90, ConfigureBase = 95 } ExceptionBaseType; typedef enum { UndefinedException = 0, EventException = 100, ExceptionEvent = EventException + ExceptionBase, ResourceEvent = EventException + ResourceBase, ResourceLimitEvent = EventException + ResourceLimitBase, TypeEvent = EventException + TypeBase, AnnotateEvent = EventException + AnnotateBase, OptionEvent = EventException + OptionBase, DelegateEvent = EventException + DelegateBase, MissingDelegateEvent = EventException + MissingDelegateBase, CorruptImageEvent = EventException + CorruptImageBase, FileOpenEvent = EventException + FileOpenBase, BlobEvent = EventException + BlobBase, StreamEvent = EventException + StreamBase, CacheEvent = EventException + CacheBase, CoderEvent = EventException + CoderBase, ModuleEvent = EventException + ModuleBase, DrawEvent = EventException + DrawBase, RenderEvent = EventException + RenderBase, ImageEvent = EventException + ImageBase, WandEvent = EventException + WandBase, TemporaryFileEvent = EventException + TemporaryFileBase, TransformEvent = EventException + TransformBase, XServerEvent = EventException + XServerBase, X11Event = EventException + X11Base, UserEvent = EventException + UserBase, MonitorEvent = EventException + MonitorBase, LocaleEvent = EventException + LocaleBase, DeprecateEvent = EventException + DeprecateBase, RegistryEvent = EventException + RegistryBase, ConfigureEvent = EventException + ConfigureBase, WarningException = 300, ExceptionWarning = WarningException + ExceptionBase, ResourceWarning = WarningException + ResourceBase, ResourceLimitWarning = WarningException + ResourceLimitBase, TypeWarning = WarningException + TypeBase, AnnotateWarning = WarningException + AnnotateBase, OptionWarning = WarningException + OptionBase, DelegateWarning = WarningException + DelegateBase, MissingDelegateWarning = WarningException + MissingDelegateBase, CorruptImageWarning = WarningException + CorruptImageBase, FileOpenWarning = WarningException + FileOpenBase, BlobWarning = WarningException + BlobBase, StreamWarning = WarningException + StreamBase, CacheWarning = WarningException + CacheBase, CoderWarning = WarningException + CoderBase, ModuleWarning = WarningException + ModuleBase, DrawWarning = WarningException + DrawBase, RenderWarning = WarningException + RenderBase, ImageWarning = WarningException + ImageBase, WandWarning = WarningException + WandBase, TemporaryFileWarning = WarningException + TemporaryFileBase, TransformWarning = WarningException + TransformBase, XServerWarning = WarningException + XServerBase, X11Warning = WarningException + X11Base, UserWarning = WarningException + UserBase, MonitorWarning = WarningException + MonitorBase, LocaleWarning = WarningException + LocaleBase, DeprecateWarning = WarningException + DeprecateBase, RegistryWarning = WarningException + RegistryBase, ConfigureWarning = WarningException + ConfigureBase, ErrorException = 400, ExceptionError = ErrorException + ExceptionBase, ResourceError = ErrorException + ResourceBase, ResourceLimitError = ErrorException + ResourceLimitBase, TypeError = ErrorException + TypeBase, AnnotateError = ErrorException + AnnotateBase, OptionError = ErrorException + OptionBase, DelegateError = ErrorException + DelegateBase, MissingDelegateError = ErrorException + MissingDelegateBase, CorruptImageError = ErrorException + CorruptImageBase, FileOpenError = ErrorException + FileOpenBase, BlobError = ErrorException + BlobBase, StreamError = ErrorException + StreamBase, CacheError = ErrorException + CacheBase, CoderError = ErrorException + CoderBase, ModuleError = ErrorException + ModuleBase, DrawError = ErrorException + DrawBase, RenderError = ErrorException + RenderBase, ImageError = ErrorException + ImageBase, WandError = ErrorException + WandBase, TemporaryFileError = ErrorException + TemporaryFileBase, TransformError = ErrorException + TransformBase, XServerError = ErrorException + XServerBase, X11Error = ErrorException + X11Base, UserError = ErrorException + UserBase, MonitorError = ErrorException + MonitorBase, LocaleError = ErrorException + LocaleBase, DeprecateError = ErrorException + DeprecateBase, RegistryError = ErrorException + RegistryBase, ConfigureError = ErrorException + ConfigureBase, FatalErrorException = 700, ExceptionFatalError = FatalErrorException + ExceptionBase, ResourceFatalError = FatalErrorException + ResourceBase, ResourceLimitFatalError = FatalErrorException + ResourceLimitBase, TypeFatalError = FatalErrorException + TypeBase, AnnotateFatalError = FatalErrorException + AnnotateBase, OptionFatalError = FatalErrorException + OptionBase, DelegateFatalError = FatalErrorException + DelegateBase, MissingDelegateFatalError = FatalErrorException + MissingDelegateBase, CorruptImageFatalError = FatalErrorException + CorruptImageBase, FileOpenFatalError = FatalErrorException + FileOpenBase, BlobFatalError = FatalErrorException + BlobBase, StreamFatalError = FatalErrorException + StreamBase, CacheFatalError = FatalErrorException + CacheBase, CoderFatalError = FatalErrorException + CoderBase, ModuleFatalError = FatalErrorException + ModuleBase, DrawFatalError = FatalErrorException + DrawBase, RenderFatalError = FatalErrorException + RenderBase, ImageFatalError = FatalErrorException + ImageBase, WandFatalError = FatalErrorException + WandBase, TemporaryFileFatalError = FatalErrorException + TemporaryFileBase, TransformFatalError = FatalErrorException + TransformBase, XServerFatalError = FatalErrorException + XServerBase, X11FatalError = FatalErrorException + X11Base, UserFatalError = FatalErrorException + UserBase, MonitorFatalError = FatalErrorException + MonitorBase, LocaleFatalError = FatalErrorException + LocaleBase, DeprecateFatalError = FatalErrorException + DeprecateBase, RegistryFatalError = FatalErrorException + RegistryBase, ConfigureFatalError = FatalErrorException + ConfigureBase } ExceptionType; /* Typedef declarations. */ /* ExceptionInfo is used to report exceptions to higher level routines, and to the user. */ typedef struct _ExceptionInfo { /* Exception severity, reason, and description */ ExceptionType severity; char *reason, *description; /* Value of errno (or equivalent) when exception was thrown. */ int error_number; /* Reporting source module, function (if available), and source module line. */ char *module, *function; unsigned long line; /* Structure sanity check */ unsigned long signature; } ExceptionInfo; /* Exception typedef declarations. */ typedef void (*ErrorHandler)(const ExceptionType,const char *,const char *); typedef void (*FatalErrorHandler)(const ExceptionType,const char *,const char *) MAGICK_FUNC_NORETURN; typedef void (*WarningHandler)(const ExceptionType,const char *,const char *); /* Exception declarations. */ extern MagickExport const char *GetLocaleExceptionMessage(const ExceptionType,const char *), *GetLocaleMessage(const char *); extern MagickExport ErrorHandler SetErrorHandler(ErrorHandler); extern MagickExport FatalErrorHandler SetFatalErrorHandler(FatalErrorHandler); extern MagickExport void CatchException(const ExceptionInfo *), CopyException(ExceptionInfo *copy, const ExceptionInfo *original), DestroyExceptionInfo(ExceptionInfo *), GetExceptionInfo(ExceptionInfo *), MagickError(const ExceptionType,const char *,const char *), MagickFatalError(const ExceptionType,const char *,const char *) MAGICK_FUNC_NORETURN, MagickWarning(const ExceptionType,const char *,const char *), _MagickError(const ExceptionType,const char *,const char *), _MagickFatalError(const ExceptionType,const char *,const char *) MAGICK_FUNC_NORETURN, _MagickWarning(const ExceptionType,const char *,const char *), SetExceptionInfo(ExceptionInfo *,ExceptionType), ThrowException(ExceptionInfo *,const ExceptionType,const char *,const char *), ThrowLoggedException(ExceptionInfo *exception, const ExceptionType severity, const char *reason,const char *description,const char *module, const char *function,const unsigned long line); extern MagickExport WarningHandler SetWarningHandler(WarningHandler); /* Exception define definitions. */ #include #if defined(MAGICK_IMPLEMENTATION) # include "magick/error-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* !defined(_MAGICK_ERROR_H) */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/forward.h ================================================ /* Copyright (C) 2007 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Forward declarations for types used in public structures. */ #ifndef _MAGICK_FORWARD_H #define _MAGICK_FORWARD_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif typedef struct _Image *ImagePtr; typedef struct _Ascii85Info* _Ascii85InfoPtr_; typedef struct _BlobInfo* _BlobInfoPtr_; typedef struct _CacheInfo* _CacheInfoPtr_; typedef struct _ImageAttribute* _ImageAttributePtr_; typedef struct _SemaphoreInfo* _SemaphoreInfoPtr_; typedef struct _ThreadViewSet* _ThreadViewSetPtr_; typedef void *ViewInfo; #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_FORWARD_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/fx.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image FX Methods. */ #ifndef _MAGICK_FX_H #define _MAGICK_FX_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *CharcoalImage(const Image *,const double,const double,ExceptionInfo *), *ColorizeImage(const Image *,const char *,const PixelPacket,ExceptionInfo *), *ImplodeImage(const Image *,const double,ExceptionInfo *), *MorphImages(const Image *,const unsigned long,ExceptionInfo *), *OilPaintImage(const Image *,const double,ExceptionInfo *), *SteganoImage(const Image *,const Image *,ExceptionInfo *), *StereoImage(const Image *,const Image *,ExceptionInfo *), *SwirlImage(const Image *,double,ExceptionInfo *), *WaveImage(const Image *,const double,const double,ExceptionInfo *); extern MagickExport MagickPassFail ColorMatrixImage(Image *image,const unsigned int order,const double *matrix), SolarizeImage(Image *,const double); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_FX_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/gem.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Graphic Gems - Graphic Support Methods. */ #ifndef _MAGICK_GEM_H #define _MAGICK_GEM_H #include "magick/random.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Graphic gems define declarations. */ extern MagickExport double ExpandAffine(const AffineMatrix *), GenerateDifferentialNoise(const Quantum pixel,const NoiseType noise_type, MagickRandomKernel *kernel); extern MagickExport int GetOptimalKernelWidth(const double,const double), GetOptimalKernelWidth1D(const double,const double), GetOptimalKernelWidth2D(const double,const double); extern MagickExport Quantum GenerateNoise(const Quantum,const NoiseType); extern MagickExport void Contrast(const int,Quantum *,Quantum *,Quantum *), HSLTransform(const double,const double,const double,Quantum *,Quantum *, Quantum *), HWBTransform(const double,const double,const double,Quantum *,Quantum *, Quantum *), Hull(const long,const long,const unsigned long,const unsigned long,Quantum *, Quantum *,const int), IdentityAffine(AffineMatrix *), Modulate(const double,const double,const double,Quantum *,Quantum *, Quantum *), TransformHSL(const Quantum,const Quantum,const Quantum,double *,double *, double *), TransformHWB(const Quantum,const Quantum,const Quantum,double *,double *, double *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/gradient.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Gradient Image Methods. */ #ifndef _MAGICK_GRADIENT_H #define _MAGICK_GRADIENT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" extern MagickExport MagickPassFail GradientImage(Image *,const PixelPacket *,const PixelPacket *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_GRADIENT_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/hclut.h ================================================ /* Copyright (C) 2009 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Hald CLUT implementation */ #ifndef _MAGICK_HCLUT_H #define _MAGICK_HCLUT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport MagickPassFail HaldClutImage(Image *,const Image * clut); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_HCLUT_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/image.h ================================================ /* Copyright (C) 2003 - 2019 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Methods. */ #ifndef _MAGICK_IMAGE_H #define _MAGICK_IMAGE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/forward.h" #include "magick/colorspace.h" #include "magick/error.h" #include "magick/timer.h" /* Define declarations. */ #if !defined(QuantumDepth) # define QuantumDepth 16 #endif /* Maximum unsigned RGB value which fits in the specified bits If bits <= 0, then zero is returned. If bits exceeds bits in unsigned long, then max value of unsigned long is returned. */ #define MaxValueGivenBits(bits) ((unsigned long) \ (((int) bits <= 0) ? 0 : \ ((0x01UL << (Min(sizeof(unsigned long)*8U,(size_t)bits)-1)) + \ ((0x01UL << (Min(sizeof(unsigned long)*8U,(size_t)bits)-1))-1)))) #if (QuantumDepth == 8) # define MaxColormapSize 256U # define MaxMap 255U # define MaxMapDepth 8 # define MaxMapFloat 255.0f # define MaxMapDouble 255.0 # define MaxRGB 255U # define MaxRGBFloat 255.0f # define MaxRGBDouble 255.0 # define ScaleCharToMap(value) ((unsigned char) (value)) # define ScaleCharToQuantum(value) ((Quantum) (value)) # define ScaleLongToQuantum(value) ((Quantum) ((value)/16843009UL)) # define ScaleMapToChar(value) ((unsigned int) (value)) # define ScaleMapToQuantum(value) ((Quantum) (value)) # define ScaleQuantum(quantum) ((unsigned long) (quantum)) # define ScaleQuantumToChar(quantum) ((unsigned char) (quantum)) # define ScaleQuantumToLong(quantum) ((unsigned long) (16843009UL*(quantum))) # define ScaleQuantumToMap(quantum) ((unsigned char) (quantum)) # define ScaleQuantumToShort(quantum) ((unsigned short) (257U*(quantum))) # define ScaleShortToQuantum(value) ((Quantum) ((value)/257U)) # define ScaleToQuantum(value) ((unsigned long) (value)) # define ScaleQuantumToIndex(value) ((unsigned char) (value)) typedef unsigned char Quantum; #elif (QuantumDepth == 16) # define MaxColormapSize 65536U # define MaxMap 65535U # define MaxMapDepth 16 # define MaxMapFloat 65535.0f # define MaxMapDouble 65535.0 # define MaxRGB 65535U # define MaxRGBFloat 65535.0f # define MaxRGBDouble 65535.0 # define ScaleCharToMap(value) ((unsigned short) (257U*(value))) # define ScaleCharToQuantum(value) ((Quantum) (257U*(value))) # define ScaleLongToQuantum(value) ((Quantum) ((value)/65537UL)) # define ScaleMapToChar(value) ((unsigned int) ((value)/257U)) # define ScaleMapToQuantum(value) ((Quantum) (value)) # define ScaleQuantum(quantum) ((unsigned long) ((quantum)/257UL)) # define ScaleQuantumToChar(quantum) ((unsigned char) ((quantum)/257U)) # define ScaleQuantumToLong(quantum) ((unsigned long) (65537UL*(quantum))) # define ScaleQuantumToMap(quantum) ((unsigned short) (quantum)) # define ScaleQuantumToShort(quantum) ((unsigned short) (quantum)) # define ScaleShortToQuantum(value) ((Quantum) (value)) # define ScaleToQuantum(value) ((unsigned long) (257UL*(value))) # define ScaleQuantumToIndex(value) ((unsigned short) (value)) typedef unsigned short Quantum; #elif (QuantumDepth == 32) # define MaxColormapSize 65536U # define MaxRGB 4294967295U # define MaxRGBFloat 4294967295.0f # define MaxRGBDouble 4294967295.0 # define ScaleCharToQuantum(value) ((Quantum) (16843009U*(value))) # define ScaleLongToQuantum(value) ((Quantum) ((value))) # define ScaleQuantum(quantum) ((unsigned long) ((quantum)/16843009UL)) # define ScaleQuantumToChar(quantum) ((unsigned char) ((quantum)/16843009U)) # define ScaleQuantumToLong(quantum) ((unsigned long) (quantum)) # define ScaleQuantumToShort(quantum) ((unsigned short) ((quantum)/65537U)) # define ScaleShortToQuantum(value) ((Quantum) (65537U*(value))) # define ScaleToQuantum(value) ((unsigned long) (16843009UL*(value))) # define ScaleQuantumToIndex(value) ((unsigned short) ((value)/65537U)) /* MaxMap defines the maximum index value for algorithms which depend on lookup tables (e.g. colorspace transformations and normalization). When MaxMap is less than MaxRGB it is necessary to downscale samples to fit the range of MaxMap. The number of bits which are effectively preserved depends on the size of MaxMap. MaxMap should be a multiple of 255 and no larger than MaxRGB. Note that tables can become quite large and as the tables grow larger it may take more time to compute the table than to process the image. */ #define MaxMap 65535U #define MaxMapDepth 16 #define MaxMapFloat 65535.0f #define MaxMapDouble 65535.0 #if MaxMap == 65535U # define ScaleCharToMap(value) ((unsigned short) (257U*(value))) # define ScaleMapToChar(value) ((unsigned int) ((value)/257U)) # define ScaleMapToQuantum(value) ((Quantum) (65537U*(value))) # define ScaleQuantumToMap(quantum) ((unsigned short) ((quantum)/65537U)) #else # define ScaleCharToMap(value) ((unsigned short) ((MaxMap/255U)*(value))) # define ScaleMapToChar(value) ((unsigned int) ((value)/(MaxMap/255U))) # define ScaleMapToQuantum(value) ((Quantum) ((MaxRGB/MaxMap)*(value))) # define ScaleQuantumToMap(quantum) ((unsigned short) ((quantum)/(MaxRGB/MaxMap))) #endif typedef unsigned int Quantum; #else # error "Specified value of QuantumDepth is not supported" #endif #define OpaqueOpacity 0UL #define TransparentOpacity MaxRGB #define RoundDoubleToQuantum(value) ((Quantum) (value < 0.0 ? 0U : \ (value > MaxRGBDouble) ? MaxRGB : value + 0.5)) #define RoundFloatToQuantum(value) ((Quantum) (value < 0.0f ? 0U : \ (value > MaxRGBFloat) ? MaxRGB : value + 0.5f)) #define ConstrainToRange(min,max,value) (value < min ? min : \ (value > max) ? max : value) #define ConstrainToQuantum(value) ConstrainToRange(0,MaxRGB,value) #define ScaleAnyToQuantum(x,max_value) \ ((Quantum) (((double) MaxRGBDouble*x)/max_value+0.5)) #define MagickBoolToString(value) (value != MagickFalse ? "True" : "False") /* Return MagickTrue if channel is enabled in channels. Allows using code to adapt if ChannelType enumeration is changed to bit masks. */ #define MagickChannelEnabled(channels,channel) ((channels == AllChannels) || (channels == channel)) /* Deprecated defines. */ #define RunlengthEncodedCompression RLECompression #define RoundSignedToQuantum(value) RoundDoubleToQuantum(value) #define RoundToQuantum(value) RoundDoubleToQuantum(value) /* Enum declarations. */ typedef enum { UnspecifiedAlpha, AssociatedAlpha, UnassociatedAlpha } AlphaType; typedef enum { UndefinedChannel, RedChannel, /* RGB Red channel */ CyanChannel, /* CMYK Cyan channel */ GreenChannel, /* RGB Green channel */ MagentaChannel, /* CMYK Magenta channel */ BlueChannel, /* RGB Blue channel */ YellowChannel, /* CMYK Yellow channel */ OpacityChannel, /* Opacity channel */ BlackChannel, /* CMYK Black (K) channel */ MatteChannel, /* Same as Opacity channel (deprecated) */ AllChannels, /* Color channels */ GrayChannel /* Color channels represent an intensity. */ } ChannelType; typedef enum { UndefinedClass, DirectClass, PseudoClass } ClassType; typedef enum { UndefinedCompositeOp = 0, OverCompositeOp, InCompositeOp, OutCompositeOp, AtopCompositeOp, XorCompositeOp, PlusCompositeOp, MinusCompositeOp, AddCompositeOp, SubtractCompositeOp, DifferenceCompositeOp, MultiplyCompositeOp, BumpmapCompositeOp, CopyCompositeOp, CopyRedCompositeOp, CopyGreenCompositeOp, CopyBlueCompositeOp, CopyOpacityCompositeOp, ClearCompositeOp, DissolveCompositeOp, DisplaceCompositeOp, ModulateCompositeOp, ThresholdCompositeOp, NoCompositeOp, DarkenCompositeOp, LightenCompositeOp, HueCompositeOp, SaturateCompositeOp, ColorizeCompositeOp, LuminizeCompositeOp, ScreenCompositeOp, OverlayCompositeOp, CopyCyanCompositeOp, CopyMagentaCompositeOp, CopyYellowCompositeOp, CopyBlackCompositeOp, DivideCompositeOp, HardLightCompositeOp, ExclusionCompositeOp, ColorDodgeCompositeOp, ColorBurnCompositeOp, SoftLightCompositeOp, LinearBurnCompositeOp, LinearDodgeCompositeOp, LinearLightCompositeOp, VividLightCompositeOp, PinLightCompositeOp, HardMixCompositeOp } CompositeOperator; typedef enum { UndefinedCompression, NoCompression, BZipCompression, FaxCompression, Group3Compression = FaxCompression, Group4Compression, JPEGCompression, LosslessJPEGCompression, LZWCompression, RLECompression, ZipCompression, LZMACompression, /* Lempel-Ziv-Markov chain algorithm */ JPEG2000Compression, /* ISO/IEC std 15444-1 */ JBIG1Compression, /* ISO/IEC std 11544 / ITU-T rec T.82 */ JBIG2Compression, /* ISO/IEC std 14492 / ITU-T rec T.88 */ ZSTDCompression, /* Facebook's Zstandard compression */ WebPCompression /* Google's WebP compression */ } CompressionType; typedef enum { UndefinedDispose, NoneDispose, BackgroundDispose, PreviousDispose } DisposeType; typedef enum { UndefinedEndian, LSBEndian, /* "little" endian */ MSBEndian, /* "big" endian */ NativeEndian /* native endian */ } EndianType; typedef enum { UndefinedFilter, PointFilter, BoxFilter, TriangleFilter, HermiteFilter, HanningFilter, HammingFilter, BlackmanFilter, GaussianFilter, QuadraticFilter, CubicFilter, CatromFilter, MitchellFilter, LanczosFilter, BesselFilter, SincFilter } FilterTypes; typedef enum { #undef NoValue NoValue = 0x00000, #undef XValue XValue = 0x00001, #undef YValue YValue = 0x00002, #undef WidthValue WidthValue = 0x00004, #undef HeightValue HeightValue = 0x00008, #undef AllValues AllValues = 0x0000F, #undef XNegative XNegative = 0x00010, #undef YNegative YNegative = 0x00020, PercentValue = 0x01000, /* % */ AspectValue = 0x02000, /* ! */ LessValue = 0x04000, /* < */ GreaterValue = 0x08000, /* > */ AreaValue = 0x10000, /* @ */ MinimumValue = 0x20000 /* ^ */ } GeometryFlags; typedef enum { #undef ForgetGravity ForgetGravity, #undef NorthWestGravity NorthWestGravity, #undef NorthGravity NorthGravity, #undef NorthEastGravity NorthEastGravity, #undef WestGravity WestGravity, #undef CenterGravity CenterGravity, #undef EastGravity EastGravity, #undef SouthWestGravity SouthWestGravity, #undef SouthGravity SouthGravity, #undef SouthEastGravity SouthEastGravity, #undef StaticGravity StaticGravity } GravityType; typedef enum { UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, OptimizeType } ImageType; typedef enum { UndefinedInterlace, NoInterlace, LineInterlace, PlaneInterlace, PartitionInterlace } InterlaceType; typedef enum { UndefinedMode, FrameMode, UnframeMode, ConcatenateMode } MontageMode; typedef enum { UniformNoise, GaussianNoise, MultiplicativeGaussianNoise, ImpulseNoise, LaplacianNoise, PoissonNoise, /* Below added on 2012-03-17 */ RandomNoise, UndefinedNoise } NoiseType; /* Image orientation. Based on TIFF standard values (also EXIF). */ typedef enum /* Exif / Row 0 / Column 0 */ /* Orientation / edge / edge */ { /* ----------- / -------- / -------- */ UndefinedOrientation, /* 0 / Unknown / Unknown */ TopLeftOrientation, /* 1 / Left / Top */ TopRightOrientation, /* 2 / Right / Top */ BottomRightOrientation, /* 3 / Right / Bottom */ BottomLeftOrientation, /* 4 / Left / Bottom */ LeftTopOrientation, /* 5 / Top / Left */ RightTopOrientation, /* 6 / Top / Right */ RightBottomOrientation, /* 7 / Bottom / Right */ LeftBottomOrientation /* 8 / Bottom / Left */ } OrientationType; typedef enum { UndefinedPreview = 0, RotatePreview, ShearPreview, RollPreview, HuePreview, SaturationPreview, BrightnessPreview, GammaPreview, SpiffPreview, DullPreview, GrayscalePreview, QuantizePreview, DespecklePreview, ReduceNoisePreview, AddNoisePreview, SharpenPreview, BlurPreview, ThresholdPreview, EdgeDetectPreview, SpreadPreview, SolarizePreview, ShadePreview, RaisePreview, SegmentPreview, SwirlPreview, ImplodePreview, WavePreview, OilPaintPreview, CharcoalDrawingPreview, JPEGPreview } PreviewType; typedef enum { UndefinedIntent, SaturationIntent, PerceptualIntent, AbsoluteIntent, RelativeIntent } RenderingIntent; typedef enum { UndefinedResolution, PixelsPerInchResolution, PixelsPerCentimeterResolution } ResolutionType; /* Typedef declarations. */ typedef struct _AffineMatrix { double sx, rx, ry, sy, tx, ty; } AffineMatrix; typedef struct _PrimaryInfo { double x, y, z; } PrimaryInfo; typedef struct _ChromaticityInfo { PrimaryInfo red_primary, green_primary, blue_primary, white_point; } ChromaticityInfo; #if defined(MAGICK_IMPLEMENTATION) /* Useful macros for accessing PixelPacket members in a generic way. */ # define GetRedSample(p) ((p)->red) # define GetGreenSample(p) ((p)->green) # define GetBlueSample(p) ((p)->blue) # define GetOpacitySample(p) ((p)->opacity) # define SetRedSample(q,value) ((q)->red=(value)) # define SetGreenSample(q,value) ((q)->green=(value)) # define SetBlueSample(q,value) ((q)->blue=(value)) # define SetOpacitySample(q,value) ((q)->opacity=(value)) # define GetGraySample(p) ((p)->red) # define SetGraySample(q,value) ((q)->red=(q)->green=(q)->blue=(value)) # define GetYSample(p) ((p)->red) # define GetCbSample(p) ((p)->green) # define GetCrSample(p) ((p)->blue) # define SetYSample(q,value) ((q)->red=(value)) # define SetCbSample(q,value) ((q)->green=(value)) # define SetCrSample(q,value) ((q)->blue=(value)) # define GetCyanSample(p) ((p)->red) # define GetMagentaSample(p) ((p)->green) # define GetYellowSample(p) ((p)->blue) # define GetBlackSample(p) ((p)->opacity) # define SetCyanSample(q,value) ((q)->red=(value)) # define SetMagentaSample(q,value) ((q)->green=(value)) # define SetYellowSample(q,value) ((q)->blue=(value)) # define SetBlackSample(q,value) ((q)->opacity=(value)) # define ClearPixelPacket(q) ((q)->red=(q)->green=(q)->blue=(q)->opacity=0) #endif /* defined(MAGICK_IMPLEMENTATION) */ typedef struct _PixelPacket { #if defined(WORDS_BIGENDIAN) /* RGBA */ #define MAGICK_PIXELS_RGBA 1 Quantum red, green, blue, opacity; #else /* BGRA (as used by Microsoft Windows DIB) */ #define MAGICK_PIXELS_BGRA 1 Quantum blue, green, red, opacity; #endif } PixelPacket; typedef struct _DoublePixelPacket { double red, green, blue, opacity; } DoublePixelPacket; typedef struct _FloatPixelPacket { float red, green, blue, opacity; } FloatPixelPacket; /* ErrorInfo is used to record statistical difference (error) information based on computed Euclidean distance in RGB space. */ typedef struct _ErrorInfo { double mean_error_per_pixel, /* Average error per pixel (absolute range) */ normalized_mean_error, /* Average error per pixel (normalized to 1.0) */ normalized_maximum_error; /* Maximum error encountered (normalized to 1.0) */ } ErrorInfo; typedef struct _FrameInfo { unsigned long width, height; long x, y, inner_bevel, outer_bevel; } FrameInfo; typedef Quantum IndexPacket; typedef struct _LongPixelPacket { unsigned long red, green, blue, opacity; } LongPixelPacket; typedef struct _MontageInfo { char *geometry, *tile, *title, *frame, *texture, *font; double pointsize; unsigned long border_width; unsigned int shadow; PixelPacket fill, stroke, background_color, border_color, matte_color; GravityType gravity; char filename[MaxTextExtent]; unsigned long signature; } MontageInfo; typedef struct _ProfileInfo { size_t length; char *name; unsigned char *info; } ProfileInfo; typedef struct _RectangleInfo { unsigned long width, height; long x, y; } RectangleInfo; typedef struct _SegmentInfo { double x1, y1, x2, y2; } SegmentInfo; struct _ImageExtra; /* forward decl.; see member "extra" below */ typedef struct _Image { ClassType storage_class; /* DirectClass (TrueColor) or PseudoClass (colormapped) */ ColorspaceType colorspace; /* Current image colorspace/model */ CompressionType compression; /* Compression algorithm to use when encoding image */ MagickBool dither, /* True if image is to be dithered */ matte; /* True if image has an opacity (alpha) channel */ unsigned long columns, /* Number of image columns */ rows; /* Number of image rows */ unsigned int colors, /* Current number of colors in PseudoClass colormap */ depth; /* Bits of precision to preserve in color quantum */ PixelPacket *colormap; /* Pseudoclass colormap array */ PixelPacket background_color, /* Background color */ border_color, /* Border color */ matte_color; /* Matte (transparent) color */ double gamma; /* Image gamma (e.g. 0.45) */ ChromaticityInfo chromaticity; /* Red, green, blue, and white chromaticity values */ OrientationType orientation; /* Image orientation */ RenderingIntent rendering_intent; /* Rendering intent */ ResolutionType units; /* Units of image resolution (density) */ char *montage, /* Tile size and offset within an image montage */ *directory, /* Tile names from within an image montage */ *geometry; /* Composite/Crop options */ long offset; /* Offset to start of image data */ double x_resolution, /* Horizontal resolution (also see units) */ y_resolution; /* Vertical resolution (also see units) */ RectangleInfo page, /* Offset to apply when placing image */ tile_info; /* Subregion tile dimensions and offset */ double blur, /* Amount of blur to apply when zooming image */ fuzz; /* Colors within this distance match target color */ FilterTypes filter; /* Filter to use when zooming image */ InterlaceType interlace; /* Interlace pattern to use when writing image */ EndianType endian; /* Byte order to use when writing image */ GravityType gravity; /* Image placement gravity */ CompositeOperator compose; /* Image placement composition (default OverCompositeOp) */ DisposeType dispose; /* GIF disposal option */ unsigned long scene, /* Animation frame scene number */ delay, /* Animation frame scene delay */ iterations, /* Animation iterations */ total_colors; /* Number of unique colors. See GetNumberColors() */ long start_loop; /* Animation frame number to start looping at */ ErrorInfo error; /* Computed image comparison or quantization error */ TimerInfo timer; /* Operation micro-timer */ void *client_data; /* User specified opaque data pointer */ /* Output file name. A colon delimited format identifier may be prepended to the file name in order to force a particular output format. Otherwise the file extension is used. If no format prefix or file extension is present, then the output format is determined by the 'magick' field. */ char filename[MaxTextExtent]; /* Original file name (name of input image file) */ char magick_filename[MaxTextExtent]; /* File format of the input file, and the default output format. The precedence when selecting the output format is: 1) magick prefix to file name (e.g. "jpeg:foo). 2) file name extension. (e.g. "foo.jpg") 3) content of this magick field. */ char magick[MaxTextExtent]; /* Original image width (before transformations) */ unsigned long magick_columns; /* Original image height (before transformations) */ unsigned long magick_rows; ExceptionInfo exception; /* Any error associated with this image frame */ struct _Image *previous, /* Pointer to previous frame */ *next; /* Pointer to next frame */ /* To be added here for a later release: quality? subsampling video black/white setup levels (ReferenceBlack/ReferenceWhite) sample format (integer/float) */ /* Only private members appear past this point */ void /* Private, Embedded profiles */ *profiles; unsigned int is_monochrome, /* Private, True if image is known to be monochrome */ is_grayscale, /* Private, True if image is known to be grayscale */ taint; /* Private, True if image has not been modifed */ /* Allow for expansion of Image without increasing its size. The internals are defined only in image.c. Clients outside of image.c can access the internals via the provided access functions (see below). This location in Image used to be occupied by Image *clip_mask. The clip_mask member now lives in _ImageExtra. */ struct _ImageExtra *extra; MagickBool ping; /* Private, if true, pixels are undefined */ _CacheInfoPtr_ cache; /* Private, image pixel cache */ _ThreadViewSetPtr_ default_views; /* Private, default cache views */ _ImageAttributePtr_ attributes; /* Private, Image attribute list */ _Ascii85InfoPtr_ ascii85; /* Private, supports huffman encoding */ _BlobInfoPtr_ blob; /* Private, file I/O object */ long reference_count; /* Private, Image reference count */ _SemaphoreInfoPtr_ semaphore; /* Private, Per image lock (for reference count) */ unsigned int logging; /* Private, True if logging is enabled */ struct _Image *list; /* Private, used only by display */ unsigned long signature; /* Private, Unique code to validate structure */ } Image; typedef struct _ImageInfo { CompressionType compression; /* Image compression to use while decoding */ MagickBool temporary, /* Remove file "filename" once it has been read. */ adjoin, /* If True, join multiple frames into one file */ antialias; /* If True, antialias while rendering */ unsigned long subimage, /* Starting image scene ID to select */ subrange, /* Span of image scene IDs (from starting scene) to select */ depth; /* Number of quantum bits to preserve while encoding */ char *size, /* Desired/known dimensions to use when decoding image */ *tile, /* Deprecated, name of image to tile on background */ *page; /* Output page size & offset */ InterlaceType interlace; /* Interlace scheme to use when decoding image */ EndianType endian; /* Select MSB/LSB endian output for TIFF format */ ResolutionType units; /* Units to apply when evaluating the density option */ unsigned long quality; /* Compression quality factor (format specific) */ char *sampling_factor, /* JPEG, MPEG, and YUV chroma downsample factor */ *server_name, /* X11 server display specification */ *font, /* Font name to use for text annotations */ *texture, /* Name of texture image to use for background fills */ *density; /* Image resolution (also see units) */ double pointsize; /* Font pointsize */ double fuzz; /* Colors within this distance are a match */ PixelPacket pen, /* Stroke or fill color while drawing */ background_color, /* Background color */ border_color, /* Border color (color surrounding frame) */ matte_color; /* Matte color (frame color) */ MagickBool dither, /* If true, dither image while writing */ monochrome, /* If true, use monochrome format */ progress; /* If true, show progress indication */ ColorspaceType colorspace; /* Colorspace representations of image pixels */ ImageType type; /* Desired image type (used while reading or writing) */ long group; /* X11 window group ID */ unsigned int verbose; /* If non-zero, display high-level processing */ char *view, /* FlashPIX view specification */ *authenticate; /* Password used to decrypt file */ void *client_data; /* User-specified data to pass to coder */ FILE *file; /* If not null, stdio FILE * to read image from (fopen mode "rb") or write image to (fopen mode "rb+"). */ char magick[MaxTextExtent], /* File format to read. Overrides file extension */ filename[MaxTextExtent]; /* File name to read */ /* Only private members appear past this point */ _CacheInfoPtr_ cache; /* Private. Used to pass image via open cache */ void *definitions; /* Private. Map of coder specific options passed by user. Use AddDefinitions, RemoveDefinitions, & AccessDefinition to access and manipulate this data. */ Image *attributes; /* Private. Image attribute list */ MagickBool ping; /* Private, if true, read file header only */ PreviewType preview_type; /* Private, used by PreviewImage */ MagickBool affirm; /* Private, when true do not intuit image format */ _BlobInfoPtr_ blob; /* Private, used to pass in open blob */ size_t length; /* Private, used to pass in open blob length */ char unique[MaxTextExtent], /* Private, passes temporary filename to TranslateText */ zero[MaxTextExtent]; /* Private, passes temporary filename to TranslateText */ unsigned long signature; /* Private, used to validate structure */ } ImageInfo; /* Image utilities methods. */ extern MagickExport ExceptionType CatchImageException(Image *); extern MagickExport Image *AllocateImage(const ImageInfo *), *AppendImages(const Image *,const unsigned int,ExceptionInfo *), *CloneImage(const Image *,const unsigned long,const unsigned long, const unsigned int,ExceptionInfo *), *GetImageClipMask(const Image *,ExceptionInfo *), *GetImageCompositeMask(const Image *,ExceptionInfo *), /*to support SVG masks*/ *ReferenceImage(Image *); extern MagickExport ImageInfo *CloneImageInfo(const ImageInfo *); extern MagickExport const char *AccessDefinition(const ImageInfo *image_info,const char *magick, const char *key); extern MagickExport int GetImageGeometry(const Image *,const char *,const unsigned int, RectangleInfo *); /* Functions which return unsigned int as a True/False boolean value */ extern MagickExport MagickBool IsTaintImage(const Image *), IsSubimage(const char *,const MagickBool); /* Functions which return unsigned int to indicate operation pass/fail */ extern MagickExport MagickPassFail AddDefinition(ImageInfo *image_info,const char *magick, const char *key, const char *value, ExceptionInfo *exception), AddDefinitions(ImageInfo *image_info,const char *options, ExceptionInfo *exception), AnimateImages(const ImageInfo *image_info,Image *image), ClipImage(Image *image), ClipPathImage(Image *image,const char *pathname,const MagickBool inside), CompositeMaskImage(Image *image), /*to support SVG masks*/ CompositePathImage(Image *image,const char *pathname,const MagickBool inside), /*to support SVG masks*/ DisplayImages(const ImageInfo *image_info,Image *image), RemoveDefinitions(const ImageInfo *image_info,const char *options), ResetImagePage(Image *image,const char *page), SetImage(Image *image,const Quantum), SetImageEx(Image *image,const Quantum opacity,ExceptionInfo *exception), SetImageColor(Image *image,const PixelPacket *pixel), SetImageColorRegion(Image *image,long x,long y,unsigned long width, unsigned long height,const PixelPacket *pixel), SetImageClipMask(Image *image,const Image *clip_mask), SetImageCompositeMask(Image *image,const Image *composite_mask), /*to support SVG masks*/ SetImageDepth(Image *image,const unsigned long), SetImageInfo(ImageInfo *image_info,const unsigned int flags,ExceptionInfo *exception), SetImageType(Image *image,const ImageType), StripImage(Image *image), SyncImage(Image *image); extern MagickExport void AllocateNextImage(const ImageInfo *,Image *), DestroyImage(Image *), DestroyImageInfo(ImageInfo *), GetImageException(Image *,ExceptionInfo *), GetImageInfo(ImageInfo *), ModifyImage(Image **,ExceptionInfo *), SetImageOpacity(Image *,const unsigned int); /* provide public access to the clip_mask member of Image */ extern MagickExport Image **ImageGetClipMask(const Image *) MAGICK_FUNC_PURE; /* provide public access to the composite_mask member of Image */ extern MagickExport Image **ImageGetCompositeMask(const Image *) MAGICK_FUNC_PURE; #if defined(MAGICK_IMPLEMENTATION) /* SetImageInfo flags specification. */ # define SETMAGICK_FALSE 0x00000 /* MagickFalse ("read") */ # define SETMAGICK_TRUE 0x00001 /* MagickTrue ("write+rectify") */ # define SETMAGICK_READ 0x00002 /* Filespec will be read */ # define SETMAGICK_WRITE 0x00004 /* Filespec will be written */ # define SETMAGICK_RECTIFY 0x00008 /* Look for adjoin in filespec */ #include "magick/image-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_IMAGE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/list.h ================================================ /* Copyright (C) 2003-2018 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image List Methods. */ #ifndef _MAGICK_LIST_H #define _MAGICK_LIST_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif extern MagickExport Image *CloneImageList(const Image *,ExceptionInfo *), *GetFirstImageInList(const Image *) MAGICK_FUNC_PURE, *GetImageFromList(const Image *,const long) MAGICK_FUNC_PURE, *GetLastImageInList(const Image *) MAGICK_FUNC_PURE, *GetNextImageInList(const Image *) MAGICK_FUNC_PURE, *GetPreviousImageInList(const Image *) MAGICK_FUNC_PURE, **ImageListToArray(const Image *,ExceptionInfo *), *NewImageList(void) MAGICK_FUNC_CONST, *RemoveLastImageFromList(Image **), *RemoveFirstImageFromList(Image **), *SplitImageList(Image *), *SyncNextImageInList(const Image *); extern MagickExport long GetImageIndexInList(const Image *) MAGICK_FUNC_PURE; extern MagickExport unsigned long GetImageListLength(const Image *) MAGICK_FUNC_PURE; extern MagickExport void AppendImageToList(Image **,Image *), DeleteImageFromList(Image **), DestroyImageList(Image *), InsertImageInList(Image **,Image *), PrependImageToList(Image **,Image *), ReplaceImageInList(Image **images,Image *image), ReverseImageList(Image **), SpliceImageIntoList(Image **,const unsigned long,Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/log.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Log methods. */ #ifndef _MAGICK_LOG_H #define _MAGICK_LOG_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Define declarations. */ #define MagickLogFilename "log.mgk" /* Obtain the current C function name (if possible) */ # if !defined(GetCurrentFunction) # if (((defined(__cplusplus) || defined(c_plusplus)) && defined(HAS_CPP__func__)) || \ (!(defined(__cplusplus) || defined(c_plusplus)) && defined(HAS_C__func__))) # define GetCurrentFunction() (__func__) # elif defined(_VISUALC_) && defined(__FUNCTION__) # define GetCurrentFunction() (__FUNCTION__) # else # define GetCurrentFunction() ("unknown") # endif # endif /* Obtain current source file, function name, and source file line, in a form acceptable for use with LogMagickEvent. */ # if !defined(GetMagickModule) # define GetMagickModule() __FILE__,GetCurrentFunction(),__LINE__ # endif /* NOTE: any changes to this effect PerlMagick */ typedef enum { UndefinedEventMask = 0x00000000, NoEventsMask = 0x00000000, ConfigureEventMask = 0x00000001, AnnotateEventMask = 0x00000002, RenderEventMask = 0x00000004, TransformEventMask = 0x00000008, LocaleEventMask = 0x00000010, CoderEventMask = 0x00000020, X11EventMask = 0x00000040, CacheEventMask = 0x00000080, BlobEventMask = 0x00000100, DeprecateEventMask = 0x00000200, UserEventMask = 0x00000400, ResourceEventMask = 0x00000800, TemporaryFileEventMask = 0x00001000, /* ExceptionEventMask = WarningEventMask | ErrorEventMask | FatalErrorEventMask */ ExceptionEventMask = 0x00070000, OptionEventMask = 0x00004000, InformationEventMask = 0x00008000, WarningEventMask = 0x00010000, ErrorEventMask = 0x00020000, FatalErrorEventMask = 0x00040000, AllEventsMask = 0x7FFFFFFF } LogEventType; typedef void (*LogMethod)(const ExceptionType,const char *); /* Method declarations. */ extern MagickExport MagickBool IsEventLogging(void) MAGICK_FUNC_PURE, LogMagickEvent(const ExceptionType type, const char *module,const char *function,const unsigned long line, const char *format,...) MAGICK_ATTRIBUTE((__format__ (__printf__,5,6))), LogMagickEventList(const ExceptionType type, const char *module,const char *function,const unsigned long line, const char *format,va_list operands) MAGICK_ATTRIBUTE((__format__ (__printf__,5,0))); extern MagickExport unsigned long SetLogEventMask(const char *events); extern MagickExport void SetLogFormat(const char *format), SetLogMethod(LogMethod); #if defined(MAGICK_IMPLEMENTATION) # include "magick/log-private.h" #endif /* MAGICK_IMPLEMENTATION */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_LOG_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/magic.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Magic methods. */ #ifndef _MAGICK_MAGIC_H #define _MAGICK_MAGIC_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Method declarations. */ extern MagickExport MagickPassFail GetMagickFileFormat(const unsigned char *header,const size_t header_length, char *format,const size_t format_length,ExceptionInfo *exception), ListMagicInfo(FILE *file,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) # include "magick/magic-private.h" #endif /* MAGICK_IMPLEMENTATION */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_MAGIC_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/magick.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Application Programming Interface declarations. */ #ifndef _MAGICK_MAGICK_H #define _MAGICK_MAGICK_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Flags to form options passed to InitializeMagickEx */ #define MAGICK_OPT_NO_SIGNAL_HANDER 0x0001 /* Don't register ANSI/POSIX signal handlers */ typedef Image *(*DecoderHandler)(const ImageInfo *,ExceptionInfo *); typedef unsigned int (*EncoderHandler)(const ImageInfo *,Image *), (*MagickHandler)(const unsigned char *,const size_t); /* Stability and usefulness of the coder. */ typedef enum { BrokenCoderClass = -1, /* Known to sometimes/often not work properly or might not be useful at all */ UnstableCoderClass = 0, /* Weak implementation, poorly designed file format, and/or hardly ever used */ StableCoderClass, /* Well maintained, but not often used */ PrimaryCoderClass /* Well maintained and commonly used */ } CoderClass; /* How the file extension should be treated (e.g. in SetImageInfo()). */ typedef enum { HintExtensionTreatment = 0, /* Extension is a useful hint to indicate format */ ObeyExtensionTreatment, /* Extension must be obeyed as format indicator */ IgnoreExtensionTreatment /* Format has no associated extension */ } ExtensionTreatment; typedef struct _MagickInfo { struct _MagickInfo *next, /* private, next member in list */ *previous; /* private, previous member in list */ const char *name; /* format ID ("magick") */ const char *description, /* format description */ *note, /* usage note for user */ *version, /* support library version */ *module; /* name of loadable module */ DecoderHandler decoder; /* function vector to decoding routine */ EncoderHandler encoder; /* function vector to encoding routine */ MagickHandler magick; /* function vector to format test routine */ void *client_data; /* arbitrary user supplied data */ MagickBool adjoin, /* coder may read/write multiple frames (default True) */ raw, /* coder requires that size be set (default False) */ stealth, /* coder should not appear in formats listing (default MagickFalse) */ seekable_stream, /* coder requires BLOB "seek" and "tell" APIs (default MagickFalse) * Note that SetImageInfo() currently always copies input * from a pipe, .gz, or .bz2 file, to a temporary file so * that it can retrieve a bit of the file header in order to * support the file header magic logic. */ blob_support, /* coder uses BLOB APIs (default True) */ thread_support; /* coder is thread safe (default True) */ CoderClass coder_class; /* Coder usefulness/stability level */ ExtensionTreatment extension_treatment; /* How much faith should be placed on file extension? */ unsigned long signature; /* private, structure validator */ } MagickInfo; /* Magick method declaractions. */ extern MagickExport char *MagickToMime(const char *magick); extern MagickExport const char *GetImageMagick(const unsigned char *magick,const size_t length); extern MagickExport MagickBool IsMagickConflict(const char *magick) MAGICK_FUNC_PURE; extern MagickExport MagickPassFail ListModuleMap(FILE *file,ExceptionInfo *exception), ListMagickInfo(FILE *file,ExceptionInfo *exception), InitializeMagickEx(const char *path, unsigned int options, ExceptionInfo *exception), UnregisterMagickInfo(const char *name); extern MagickExport void DestroyMagick(void), InitializeMagick(const char *path), PanicDestroyMagick(void); extern MagickExport const MagickInfo *GetMagickInfo(const char *name,ExceptionInfo *exception); extern MagickExport MagickInfo **GetMagickInfoArray(ExceptionInfo *exception); extern MagickExport MagickInfo *RegisterMagickInfo(MagickInfo *magick_info), *SetMagickInfo(const char *name); #if defined(MAGICK_IMPLEMENTATION) # include "magick/magick-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_MAGICK_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/magick_config.h ================================================ /* magick/magick_config_api.h. Generated from magick_config_api.h.in by configure. */ /* Defines required by */ /* Define if you have X11 library */ /* #undef HasX11 */ /* Number of bits in a pixel Quantum (8/16/32) */ #define QuantumDepth 8 /* Define to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel and VAX). */ /* #undef WORDS_BIGENDIAN */ /* Prefix Magick library symbols with a common string. */ /* #undef PREFIX_MAGICK_SYMBOLS */ /* Define to `unsigned int' if does not define. */ /* #undef size_t */ /* Define to `int' if does not define. */ /* #undef ssize_t */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/magick_types.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick types typedefs. GraphicsMagick is expected to compile with any C '89 ANSI C compiler supporting at least 16-bit 'short', 32-bit 'int', and 32-bit 'long'. It is also expected to take advantage of 64-bit LP64 and Windows WIN64 LLP64. We use C '99 style types but declare our own types so as to not depend on C '99 header files, and take care to depend only on C '89 library functions, POSIX, or well-known extensions. Any C '99 syntax used is removed if the compiler does not support it. */ #ifndef _MAGICK_TYPES_H #define _MAGICK_TYPES_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Assign ANSI C'99 stdint.h-like typedefs based on the sizes of native types magick_int8_t -- -128 to 127 magick_uint8_t -- 0 to 255 magick_int16_t -- -32,768 to 32,767 magick_uint16_t -- 0 to 65,535 magick_int32_t -- -2,147,483,648 to 2,147,483,647 magick_uint32_t -- 0 to 4,294,967,295 magick_int64_t -- -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807 magick_uint64_t -- 0 to 18,446,744,073,709,551,615 magick_uintmax_t -- largest native unsigned integer type ("%ju") 0 to UINTMAX_MAX UINTMAX_C(value) declares constant value magick_uintptr_t -- unsigned type for storing a pointer value ("%tu") 0 to UINTPTR_MAX ANSI C '89 stddef.h-like types size_t -- unsigned type representing sizes of objects ("%zu") 0 to SIZE_MAX ptrdiff_t -- signed type for subtracting two pointers ("%td") PTRDIFF_MIN to PTRDIFF_MAX IEEE Std 1003.1 (1990), 2004 types. Not part of ANSI C! ssize_t -- signed type for a count of bytes or an error indication ("%zd") ? to SSIZE_MAX */ #if (defined(WIN32) || defined(WIN64)) && \ !defined(__MINGW32__) && !defined(__MINGW64__) /* The following typedefs are used for WIN32 & WIN64 (without configure) */ typedef signed char magick_int8_t; typedef unsigned char magick_uint8_t; typedef signed short magick_int16_t; typedef unsigned short magick_uint16_t; typedef signed int magick_int32_t; # define MAGICK_INT32_F "" typedef unsigned int magick_uint32_t; # define MAGICK_UINT32_F "" typedef signed __int64 magick_int64_t; # define MAGICK_INT64_F "I64" typedef unsigned __int64 magick_uint64_t; # define MAGICK_UINT64_F "I64" typedef magick_uint64_t magick_uintmax_t; # if defined(WIN64) /* WIN64 uses the LLP64 model */ typedef unsigned long long magick_uintptr_t; # define MAGICK_SIZE_T_F "I64" # define MAGICK_SIZE_T unsigned __int64 # define MAGICK_SSIZE_T_F "I64" # define MAGICK_SSIZE_T signed __int64 # else typedef unsigned long magick_uintptr_t; # define MAGICK_SIZE_T_F "l" # define MAGICK_SIZE_T unsigned long # define MAGICK_SSIZE_T_F "l" # define MAGICK_SSIZE_T long # endif // defined(WIN64) #else /* The following typedefs are subtituted when using Unixish configure */ typedef signed char magick_int8_t; typedef unsigned char magick_uint8_t; typedef signed short magick_int16_t; typedef unsigned short magick_uint16_t; typedef signed int magick_int32_t; # define MAGICK_INT32_F "" typedef unsigned int magick_uint32_t; # define MAGICK_UINT32_F "" typedef signed long magick_int64_t; # define MAGICK_INT64_F "l" typedef unsigned long magick_uint64_t; # define MAGICK_UINT64_F "l" typedef unsigned long magick_uintmax_t; # define MAGICK_UINTMAX_F "l" typedef unsigned long magick_uintptr_t; # define MAGICK_UINTPTR_F "l" # define MAGICK_SIZE_T_F "l" # define MAGICK_SIZE_T unsigned long # define MAGICK_SSIZE_T_F "l" # define MAGICK_SSIZE_T signed long #endif /* 64-bit file and blob offset type */ typedef magick_int64_t magick_off_t; #define MAGICK_OFF_F MAGICK_INT64_F #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_TYPES_H */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/memory.h ================================================ /* Copyright (C) 2003-2020 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Memory Allocation Methods. */ #ifndef _MAGICK_MEMORY_H #define _MAGICK_MEMORY_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif typedef void *(*MagickMallocFunc)(size_t size); typedef void (*MagickFreeFunc)(void *ptr); typedef void *(*MagickReallocFunc)(void *ptr, size_t size); extern MagickExport void MagickAllocFunctions(MagickFreeFunc free_func,MagickMallocFunc malloc_func, MagickReallocFunc realloc_func), *MagickMalloc(const size_t size) MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(1), *MagickMallocAligned(const size_t alignment, const size_t size) MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(2), *MagickMallocCleared(const size_t size) MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(1), *MagickCloneMemory(void *destination,const void *source,const size_t size) MAGICK_FUNC_NONNULL, *MagickRealloc(void *memory,const size_t size) MAGICK_FUNC_MALLOC MAGICK_FUNC_ALLOC_SIZE_1ARG(2), MagickFree(void *memory), MagickFreeAligned(void *memory); #if defined(MAGICK_IMPLEMENTATION) #include "magick/memory-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/module.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Modules Methods. */ #ifndef _MAGICK_MODULE_H #define _MAGICK_MODULE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Modules declarations. */ extern MagickExport MagickPassFail ExecuteModuleProcess(const char *tag,Image **image, const int argc,char **argv); #if defined(MAGICK_IMPLEMENTATION) #include "magick/module-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/monitor.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Progress Monitor Methods. */ #ifndef _MAGICK_MONITOR_H #define _MAGICK_MONITOR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Monitor typedef declarations. */ typedef MagickPassFail (*MonitorHandler)(const char *text,const magick_int64_t quantum, const magick_uint64_t span,ExceptionInfo *exception); /* Monitor declarations. */ extern MagickExport MonitorHandler SetMonitorHandler(MonitorHandler handler); extern MagickExport MagickPassFail MagickMonitor(const char *text, const magick_int64_t quantum,const magick_uint64_t span, ExceptionInfo *exception) MAGICK_FUNC_DEPRECATED; extern MagickExport MagickPassFail MagickMonitorFormatted(const magick_int64_t quantum, const magick_uint64_t span, ExceptionInfo *exception, const char *format,...) MAGICK_ATTRIBUTE((__format__ (__printf__,4,5))); #if defined(MAGICK_IMPLEMENTATION) # include "magick/monitor-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/montage.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Montage Methods. */ #ifndef _MAGICK_MONTAGE_H #define _MAGICK_MONTAGE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *MontageImages(const Image *,const MontageInfo *,ExceptionInfo *); extern MagickExport MontageInfo *CloneMontageInfo(const ImageInfo *,const MontageInfo *); extern MagickExport void DestroyMontageInfo(MontageInfo *), GetMontageInfo(const ImageInfo *,MontageInfo *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_MONTAGE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/operator.h ================================================ /* % Copyright (C) 2004 - 2012 GraphicsMagick Group % % This program is covered by multiple licenses, which are described in % Copyright.txt. You should have received a copy of Copyright.txt with this % package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. % % Interfaces to support quantum operators. % Written by Bob Friesenhahn, March 2004. % */ #ifndef _MAGICK_OPERATOR_H #define _MAGICK_OPERATOR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ typedef enum { UndefinedQuantumOp = 0, AddQuantumOp, /* Add value */ AndQuantumOp, /* Bitwise AND value */ AssignQuantumOp, /* Direct value assignment */ DivideQuantumOp, /* Divide by value */ LShiftQuantumOp, /* Bitwise left-shift value N bits */ MultiplyQuantumOp, /* Multiply by value */ OrQuantumOp, /* Bitwise OR value */ RShiftQuantumOp, /* Bitwise right shift value */ SubtractQuantumOp, /* Subtract value */ ThresholdQuantumOp, /* Above threshold white, otherwise black */ ThresholdBlackQuantumOp, /* Below threshold is black */ ThresholdWhiteQuantumOp, /* Above threshold is white */ XorQuantumOp, /* Bitwise XOR value */ NoiseGaussianQuantumOp, /* Gaussian noise */ NoiseImpulseQuantumOp, /* Impulse noise */ NoiseLaplacianQuantumOp, /* Laplacian noise */ NoiseMultiplicativeQuantumOp, /* Multiplicative gaussian noise */ NoisePoissonQuantumOp, /* Poisson noise */ NoiseUniformQuantumOp, /* Uniform noise */ NegateQuantumOp, /* Negate (invert) channel, ignore value */ GammaQuantumOp, /* Adjust image gamma */ DepthQuantumOp, /* Adjust image depth */ /* Below added on 2008-12-13 */ LogQuantumOp, /* log(quantum*value+1)/log(value+1) */ MaxQuantumOp, /* Assign value if > quantum */ MinQuantumOp, /* Assign value if < quantum */ PowQuantumOp, /* Power function: pow(quantum,value) */ /* Below added on 2012-03-17 */ NoiseRandomQuantumOp, /* Random noise */ /* Below added on 2014-05-17 */ ThresholdBlackNegateQuantumOp, /* Below threshold is set to white */ ThresholdWhiteNegateQuantumOp /* Above threshold is set to black */ } QuantumOperator; extern MagickExport MagickPassFail QuantumOperatorImage(Image *image,const ChannelType channel, const QuantumOperator quantum_operator,const double rvalue, ExceptionInfo *exception), QuantumOperatorImageMultivalue(Image *image, const QuantumOperator quantum_operator, const char *values), QuantumOperatorRegionImage(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows, const ChannelType channel,const QuantumOperator quantum_operator, const double rvalue,ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/paint.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Paint Methods. */ #ifndef _MAGICK_PAINT_H #define _MAGICK_PAINT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "magick/render.h" extern MagickExport unsigned int ColorFloodfillImage(Image *,const DrawInfo *,const PixelPacket,const long, const long,const PaintMethod), MatteFloodfillImage(Image *,const PixelPacket,const unsigned int,const long, const long,const PaintMethod); extern MagickExport unsigned int OpaqueImage(Image *,const PixelPacket,const PixelPacket), TransparentImage(Image *,const PixelPacket,const unsigned int); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/pixel_cache.h ================================================ /* Copyright (C) 2003 - 2018 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Pixel Cache Methods. */ #ifndef _MAGICK_CACHE_H #define _MAGICK_CACHE_H #include "magick/forward.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declaractions. */ typedef enum { UndefinedVirtualPixelMethod, ConstantVirtualPixelMethod, EdgeVirtualPixelMethod, MirrorVirtualPixelMethod, TileVirtualPixelMethod } VirtualPixelMethod; /* Typedef declaractions. */ typedef _CacheInfoPtr_ Cache; /***** * * Default View interfaces * *****/ /* Read only access to a rectangular pixel region. */ MagickExport const PixelPacket *AcquireImagePixels(const Image *image,const long x,const long y, const unsigned long columns, const unsigned long rows,ExceptionInfo *exception); /* AccessImmutableIndexes() returns the read-only indexes associated with a rectangular pixel region already selected via AcquireImagePixels(). */ extern MagickExport const IndexPacket *AccessImmutableIndexes(const Image *image); /* Return one DirectClass pixel at the the specified (x,y) location. Similar function as GetOnePixel(). Note that the value returned by GetIndexes() may or may not be influenced by this function. */ extern MagickExport PixelPacket AcquireOnePixel(const Image *image,const long x,const long y, ExceptionInfo *exception); /* GetImagePixels() and GetImagePixelsEx() obtains a pixel region for read/write access. */ extern MagickExport PixelPacket *GetImagePixels(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows); extern MagickExport PixelPacket *GetImagePixelsEx(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows, ExceptionInfo *exception); /* GetImageVirtualPixelMethod() gets the "virtual pixels" method for the image. */ extern MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) MAGICK_FUNC_PURE; /* GetPixels() and AccessMutablePixels() return the pixels associated with the last call to SetImagePixels() or GetImagePixels(). */ extern MagickExport PixelPacket *GetPixels(const Image *image) MAGICK_FUNC_DEPRECATED; /* Prefer AccessMutablePixels instead */ extern MagickExport PixelPacket *AccessMutablePixels(Image *image); /* GetIndexes() and AccessMutableIndexes() return the colormap indexes associated with the last call to SetImagePixels() or GetImagePixels(). */ extern MagickExport IndexPacket *GetIndexes(const Image *image) MAGICK_FUNC_DEPRECATED; /* Prefer AccessMutableIndexes() instead */ extern MagickExport IndexPacket *AccessMutableIndexes(Image *image); /* GetOnePixel() returns a single DirectClass pixel at the specified (x,y) location. Similar to AcquireOnePixel(). It is preferred to use AcquireOnePixel() since it allows reporting to a specified exception structure. Note that the value returned by GetIndexes() is not reliably influenced by this function. */ extern MagickExport PixelPacket GetOnePixel(Image *image,const long x,const long y) MAGICK_FUNC_DEPRECATED; /* Prefer AcquireOnePixel() instead */ /* GetPixelCacheArea() returns the area (width * height in pixels) consumed by the current pixel cache. */ extern MagickExport magick_off_t GetPixelCacheArea(const Image *image); /* SetImagePixels() and SetImagePixelsEx() initialize a pixel region for write-only access. */ extern MagickExport PixelPacket *SetImagePixels(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows); extern MagickExport PixelPacket *SetImagePixelsEx(Image *image,const long x,const long y, const unsigned long columns,const unsigned long rows, ExceptionInfo *exception); /* SetImageVirtualPixelMethod() sets the "virtual pixels" method for the image. */ extern MagickExport MagickPassFail SetImageVirtualPixelMethod(const Image *image, const VirtualPixelMethod method); /* SyncImagePixels() and SyncImagePixelsEx() save the image pixels to the in-memory or disk cache. */ extern MagickExport MagickPassFail SyncImagePixels(Image *image); extern MagickExport MagickPassFail SyncImagePixelsEx(Image *image,ExceptionInfo *exception); /**** * * Cache view interfaces * ****/ /* OpenCacheView() opens a cache view. */ extern MagickExport ViewInfo *OpenCacheView(Image *image); /* CloseCacheView() closes a cache view. */ extern MagickExport void CloseCacheView(ViewInfo *view); /* AccessCacheViewPixels() returns the pixels associated with the last request to select a view pixel region (i.e. AcquireCacheViewPixels() or GetCacheViewPixels()). */ extern MagickExport PixelPacket *AccessCacheViewPixels(const ViewInfo *view) MAGICK_FUNC_PURE; /* AcquireCacheViewIndexes() returns read-only indexes associated with a cache view. */ extern MagickExport const IndexPacket *AcquireCacheViewIndexes(const ViewInfo *view) MAGICK_FUNC_PURE; /* AcquireCacheViewPixels() obtains a pixel region from a cache view for read-only access. */ extern MagickExport const PixelPacket *AcquireCacheViewPixels(ViewInfo *view, const long x,const long y, const unsigned long columns, const unsigned long rows, ExceptionInfo *exception); /* AcquireOneCacheViewPixel() returns one DirectClass pixel from a cache view. Note that the value returned by GetCacheViewIndexes() is not reliably influenced by this function. */ extern MagickExport MagickPassFail AcquireOneCacheViewPixel(ViewInfo *view,PixelPacket *pixel, const long x,const long y,ExceptionInfo *exception); /* GetCacheViewArea() returns the area (width * height in pixels) currently consumed by the pixel cache view. */ extern MagickExport magick_off_t GetCacheViewArea(const ViewInfo *view) MAGICK_FUNC_PURE; /* GetCacheViewImage() obtains the image used to allocate the cache view. */ extern Image * GetCacheViewImage(const ViewInfo *view) MAGICK_FUNC_PURE; /* GetCacheViewIndexes() returns the indexes associated with a cache view. */ extern MagickExport IndexPacket *GetCacheViewIndexes(const ViewInfo *view) MAGICK_FUNC_PURE; /* GetCacheViewPixels() obtains a pixel region from a cache view for read/write access. */ extern MagickExport PixelPacket *GetCacheViewPixels(ViewInfo *view,const long x,const long y, const unsigned long columns,const unsigned long rows, ExceptionInfo *exception); /* Obtain the offset and size of the selected region. */ extern MagickExport RectangleInfo GetCacheViewRegion(const ViewInfo *view) MAGICK_FUNC_PURE; /* SetCacheViewPixels() gets blank writeable pixels from the pixel cache view. */ extern MagickExport PixelPacket *SetCacheViewPixels(ViewInfo *view,const long x,const long y, const unsigned long columns,const unsigned long rows, ExceptionInfo *exception); /* SyncCacheViewPixels() saves any changes to the pixel cache view. */ extern MagickExport MagickPassFail SyncCacheViewPixels(const ViewInfo *view,ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) #include "magick/pixel_cache-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_CACHE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/pixel_iterator.h ================================================ /* Copyright (C) 2004-2016 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Interfaces to support simple iterative pixel read/update access within an image or between two images. These interfaces exist in order to eliminate large amounts of redundant code and to allow changing the underlying implementation without changing the using code. These interfaces intentionally omit any pixel position information in order to not constrain the implementation and to improve performance. User-provided callbacks must be thread-safe (preferably re-entrant) since they may be invoked by multiple threads. These interfaces have proven to be future safe (since implemented) and may be safely used by other applications/libraries. Written by Bob Friesenhahn, March 2004, Updated for regions 2008. */ #ifndef _PIXEL_ROW_ITERATOR_H #define _PIXEL_ROW_ITERATOR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Pixel iterator options. */ typedef struct _PixelIteratorOptions { int max_threads; /* Desired number of threads */ unsigned long signature; } PixelIteratorOptions; /* Initialize pixel iterator options with defaults. */ extern MagickExport void InitializePixelIteratorOptions(PixelIteratorOptions *options, ExceptionInfo *exception); /* Read-only access across pixel region. */ typedef MagickPassFail (*PixelIteratorMonoReadCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ const Image *const_image, /* Input image */ const PixelPacket *pixels, /* Pixel row */ const IndexPacket *indexes, /* Pixel indexes */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); extern MagickExport MagickPassFail PixelIterateMonoRead(PixelIteratorMonoReadCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const long x, const long y, const unsigned long columns, const unsigned long rows, const Image *image, ExceptionInfo *exception); typedef MagickPassFail (*PixelIteratorMonoModifyCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ Image *image, /* Modify image */ PixelPacket *pixels, /* Pixel row */ IndexPacket *indexes, /* Pixel row indexes */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); /* Write access across pixel region. */ extern MagickExport MagickPassFail PixelIterateMonoSet(PixelIteratorMonoModifyCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const long x, const long y, const unsigned long columns, const unsigned long rows, Image *image, ExceptionInfo *exception); /* Read-write access across pixel region. */ extern MagickExport MagickPassFail PixelIterateMonoModify(PixelIteratorMonoModifyCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const long x, const long y, const unsigned long columns, const unsigned long rows, Image *image, ExceptionInfo *exception); /* Read-only access across pixel regions of two images. */ typedef MagickPassFail (*PixelIteratorDualReadCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ const Image *first_image, /* First Input image */ const PixelPacket *first_pixels, /* Pixel row in first image */ const IndexPacket *first_indexes, /* Pixel row indexes in first image */ const Image *second_image, /* Second Input image */ const PixelPacket *second_pixels, /* Pixel row in second image */ const IndexPacket *second_indexes, /* Pixel row indexes in second image */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); extern MagickExport MagickPassFail PixelIterateDualRead(PixelIteratorDualReadCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *first_image, const long first_x, const long first_y, const Image *second_image, const long second_x, const long second_y, ExceptionInfo *exception); /* Read-write access across pixel regions of two images. The first (source) image is accessed read-only while the second (update) image is accessed as read-write. */ typedef MagickPassFail (*PixelIteratorDualModifyCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ const Image *source_image, /* Source image */ const PixelPacket *source_pixels, /* Pixel row in source image */ const IndexPacket *source_indexes, /* Pixel row indexes in source image */ Image *update_image, /* Update image */ PixelPacket *update_pixels, /* Pixel row in update image */ IndexPacket *update_indexes, /* Pixel row indexes in update image */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); extern MagickExport MagickPassFail PixelIterateDualModify(PixelIteratorDualModifyCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *source_image, const long source_x, const long source_y, Image *update_image, const long update_x, const long update_y, ExceptionInfo *exception); /* Read-write access across pixel regions of two images. The first (source) image is accessed read-only while the second (new) image is accessed for write (uninitialized pixels). */ typedef PixelIteratorDualModifyCallback PixelIteratorDualNewCallback; extern MagickExport MagickPassFail PixelIterateDualNew(PixelIteratorDualNewCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *source_image, const long source_x, const long source_y, Image *new_image, const long new_x, const long new_y, ExceptionInfo *exception); /* Read-read-write access across pixel regions of three images. The first two images are accessed read-only while the third is accessed as read-write. */ typedef MagickPassFail (*PixelIteratorTripleModifyCallback) ( void *mutable_data, /* User provided mutable data */ const void *immutable_data, /* User provided immutable data */ const Image *source1_image, /* Source 1 image */ const PixelPacket *source1_pixels, /* Pixel row in source 1 image */ const IndexPacket *source1_indexes, /* Pixel row indexes in source 1 image */ const Image *source2_image, /* Source 2 image */ const PixelPacket *source2_pixels, /* Pixel row in source 2 image */ const IndexPacket *source2_indexes, /* Pixel row indexes in source 2 image */ Image *update_image, /* Update image */ PixelPacket *update_pixels, /* Pixel row in update image */ IndexPacket *update_indexes, /* Pixel row indexes in update image */ const long npixels, /* Number of pixels in row */ ExceptionInfo *exception /* Exception report */ ); extern MagickExport MagickPassFail PixelIterateTripleModify(PixelIteratorTripleModifyCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *source1_image, const Image *source2_image, const long source_x, const long source_y, Image *update_image, const long update_x, const long update_y, ExceptionInfo *exception); /* Read-write access across pixel regions of two images. The first (source) image is accessed read-only while the second (new) image is accessed for write (uninitialized pixels). */ typedef PixelIteratorTripleModifyCallback PixelIteratorTripleNewCallback; extern MagickExport MagickPassFail PixelIterateTripleNew(PixelIteratorTripleNewCallback call_back, const PixelIteratorOptions *options, const char *description, void *mutable_data, const void *immutable_data, const unsigned long columns, const unsigned long rows, const Image *source1_image, const Image *source2_image, const long source_x, const long source_y, Image *new_image, const long new_x, const long new_y, ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _PIXEL_ROW_ITERATOR_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/plasma.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Plasma Methods. */ #ifndef _MAGICK_PLASMA_H #define _MAGICK_PLASMA_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" extern MagickExport MagickPassFail PlasmaImage(Image *image,const SegmentInfo *segment, unsigned long attenuate,unsigned long depth); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_PLASMA_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/profile.h ================================================ /* Copyright (C) 2004 - 2009 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Methods For Manipulating Embedded Image Profiles. */ #ifndef _MAGICK_PROFILE_H #define _MAGICK_PROFILE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ /* Retrieve a profile from the image by name. */ extern MagickExport const unsigned char *GetImageProfile(const Image* image, const char *name, size_t *length); /* Remove a profile from the image by name. */ extern MagickExport MagickPassFail DeleteImageProfile(Image *image,const char *name); /* Apply (or add) a profile to the image. */ extern MagickExport MagickPassFail ProfileImage(Image *image,const char *name,unsigned char *profile, const size_t length,MagickBool clone); /* Add (or replace) profile to the image by name. */ extern MagickExport MagickPassFail SetImageProfile(Image *image,const char *name,const unsigned char *profile, const size_t length); /* Add (or append) profile to the image by name. */ extern MagickExport MagickPassFail AppendImageProfile(Image *image,const char *name, const unsigned char *profile_chunk, const size_t chunk_length); /* Generic iterator for traversing profiles. */ typedef void *ImageProfileIterator; /* Allocate an image profile iterator which points to one before the list so NextImageProfile() must be used to advance to first entry. */ extern MagickExport ImageProfileIterator AllocateImageProfileIterator(const Image *image); /* Advance to next image profile. Name, profile, and length are updated with information on current profile. MagickFail is returned when there are no more entries. */ extern MagickExport MagickPassFail NextImageProfile(ImageProfileIterator profile_iterator,const char **name, const unsigned char **profile,size_t *length); /* Deallocate profile iterator. */ extern MagickExport void DeallocateImageProfileIterator(ImageProfileIterator profile_iterator); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_PROFILE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/quantize.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Methods to Reduce the Number of Unique Colors in an Image. */ #ifndef _MAGICK_QUANTIZE_H #define _MAGICK_QUANTIZE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Define declarations. */ #define MaxTreeDepth 8 #define NodesInAList 1536 /* Typedef declarations. */ typedef struct _QuantizeInfo { unsigned long number_colors; unsigned int tree_depth, dither; ColorspaceType colorspace; unsigned int measure_error; unsigned long signature; } QuantizeInfo; /* Quantization utilities methods. */ extern MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *); extern MagickExport unsigned int GetImageQuantizeError(Image *), MapImage(Image *,const Image *,const unsigned int), MapImages(Image *,const Image *,const unsigned int), OrderedDitherImage(Image *), QuantizeImage(const QuantizeInfo *,Image *), QuantizeImages(const QuantizeInfo *,Image *), SegmentImage(Image *,const ColorspaceType,const unsigned int,const double, const double); extern MagickExport void CompressImageColormap(Image *), DestroyQuantizeInfo(QuantizeInfo *), GetQuantizeInfo(QuantizeInfo *), GrayscalePseudoClassImage(Image *,unsigned int); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/random.h ================================================ /* Copyright (C) 2009, 2014 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Random number generator (semi-public interfaces). Currently based on George Marsaglia's multiply-with-carry generator. This is a k=2 generator with a period >2^60. */ #ifndef _MAGICK_RANDOM_H #define _MAGICK_RANDOM_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ typedef struct _MagickRandomKernel { magick_uint32_t z; magick_uint32_t w; } MagickRandomKernel; #define MAGICK_RANDOM_MAX 4294967295 /* Generate a random integer value (0 - MAGICK_RANDOM_MAX) */ MagickExport magick_uint32_t MagickRandomInteger(void); /* Generate a random double value (0.0 - 1.0) */ MagickExport double MagickRandomReal(void); #if defined(MAGICK_IMPLEMENTATION) #include "magick/random-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* ifndef _MAGICK_RANDOM_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/registry.h ================================================ /* Copyright (C) 2003-2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Magick registry methods. */ #ifndef _MAGICK_REGISTRY_H #define _MAGICK_REGISTRY_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { UndefinedRegistryType, ImageRegistryType, ImageInfoRegistryType } RegistryType; /* Magick registry methods. */ extern MagickExport Image *GetImageFromMagickRegistry(const char *name,long *id, ExceptionInfo *exception); extern MagickExport long SetMagickRegistry(const RegistryType type,const void *blob, const size_t length,ExceptionInfo *exception); extern MagickExport MagickPassFail DeleteMagickRegistry(const long id); extern MagickExport void *GetMagickRegistry(const long id,RegistryType *type,size_t *length, ExceptionInfo *exception); #if defined(MAGICK_IMPLEMENTATION) # include "magick/registry-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/render.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Drawing methods. */ #ifndef _MAGICK_RENDER_H #define _MAGICK_RENDER_H #include "magick/type.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { UndefinedAlign, LeftAlign, CenterAlign, RightAlign } AlignType; typedef enum { UserSpace, UserSpaceOnUse, ObjectBoundingBox } ClipPathUnits; typedef enum { NoDecoration, UnderlineDecoration, OverlineDecoration, LineThroughDecoration } DecorationType; typedef enum { UndefinedRule, #undef EvenOddRule EvenOddRule, NonZeroRule } FillRule; typedef enum { UndefinedGradient, LinearGradient, RadialGradient } GradientType; typedef enum { UndefinedCap, ButtCap, RoundCap, SquareCap } LineCap; typedef enum { UndefinedJoin, MiterJoin, RoundJoin, BevelJoin } LineJoin; typedef enum { PointMethod = 0, ReplaceMethod, FloodfillMethod, FillToBorderMethod, ResetMethod } PaintMethod; typedef enum { UndefinedPrimitive = 0, PointPrimitive, LinePrimitive, RectanglePrimitive, RoundRectanglePrimitive, ArcPrimitive, EllipsePrimitive, CirclePrimitive, PolylinePrimitive, PolygonPrimitive, BezierPrimitive, ColorPrimitive, MattePrimitive, TextPrimitive, ImagePrimitive, PathPrimitive } PrimitiveType; typedef enum { UndefinedReference, GradientReference } ReferenceType; typedef enum { UndefinedSpread, PadSpread, ReflectSpead, RepeatSpread } SpreadMethod; /* Typedef declarations. */ typedef struct _GradientInfo { GradientType type; PixelPacket color; SegmentInfo stop; unsigned long length; SpreadMethod spread; unsigned long signature; struct _GradientInfo *previous, *next; } GradientInfo; typedef struct _ElementReference { char *id; ReferenceType type; GradientInfo gradient; unsigned long signature; struct _ElementReference *previous, *next; } ElementReference; struct _DrawInfoExtra; /* forward decl.; see member "extra" below */ typedef struct _DrawInfo { char *primitive, *geometry; AffineMatrix affine; GravityType gravity; PixelPacket fill, stroke; double stroke_width; GradientInfo gradient; Image *fill_pattern, *tile, *stroke_pattern; unsigned int stroke_antialias, text_antialias; FillRule fill_rule; LineCap linecap; LineJoin linejoin; unsigned long miterlimit; double dash_offset; DecorationType decorate; CompositeOperator compose; char *text, *font, *family; StyleType style; StretchType stretch; unsigned long weight; char *encoding; double pointsize; char *density; AlignType align; PixelPacket undercolor, border_color; char *server_name; double *dash_pattern; /* Terminated by value 0.0 (i.e. < MagickEpsilon)*/ #if 0 char *clip_path; #endif /* Allow for expansion of DrawInfo without increasing its size. The internals are defined only in render.c. Clients outside of render.c can access the internals via the provided access functions (see below). This location in DrawInfo used to be occupied by char *clip_path. The clip_path member now lives in _DrawInfoExtra. */ struct _DrawInfoExtra *extra; SegmentInfo bounds; ClipPathUnits clip_units; Quantum opacity; unsigned int render, /* Bit fields in flags: Bit 0: should this DrawInfo should be drawn as: 0: normal (original behavior) 1: SVG compliant Bit 1: is the DrawInfo a clipping path: 0: is not a clipping path 1: is a clipping path Access to these bits should be through functions (defined in render.c): IsDrawInfoClippingPath() IsDrawInfoSVGCompliant() IsDrawInfoSVGCompliantClippingPath() SetDrawInfoClippingPath() SetDrawInfoSVGCompliant() At the present time the SVG compliance bit only affects how clipping paths are drawn. */ flags; /* previously "unused1" */ ElementReference element_reference; unsigned long signature; } DrawInfo; typedef struct _PointInfo { double x, y; } PointInfo; #if defined(MAGICK_IMPLEMENTATION) # include "magick/render-private.h" #endif /* if defined(MAGICK_IMPLEMENTATION) */ typedef struct _TypeMetric { PointInfo pixels_per_em; double ascent, descent, width, height, max_advance; SegmentInfo bounds; double underline_position, underline_thickness; } TypeMetric; /* Method declarations. */ extern MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *,const DrawInfo *); extern MagickExport MagickPassFail AnnotateImage(Image *,const DrawInfo *), DrawAffineImage(Image *,const Image *,const AffineMatrix *), DrawClipPath(Image *,const DrawInfo *,const char *), DrawImage(Image *,const DrawInfo *), DrawPatternPath(Image *,const DrawInfo *,const char *,Image **), GetTypeMetrics(Image *,const DrawInfo *,TypeMetric *); extern MagickExport void DestroyDrawInfo(DrawInfo *), GetDrawInfo(const ImageInfo *,DrawInfo *); /* provide public access to the clip_path member of DrawInfo */ extern MagickExport char **DrawInfoGetClipPath(const DrawInfo *) MAGICK_FUNC_PURE; /* provide public access to the composite_path member of DrawInfo */ extern MagickExport char **DrawInfoGetCompositePath(const DrawInfo *) MAGICK_FUNC_PURE; #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_RENDER_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/resize.h ================================================ /* Copyright (C) 2003 - 2012 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Resize Methods. */ #ifndef _MAGICK_RESIZE_H #define _MAGICK_RESIZE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ #define DefaultResizeFilter LanczosFilter #define DefaultThumbnailFilter BoxFilter extern MagickExport Image *MagnifyImage(const Image *,ExceptionInfo *), *MinifyImage(const Image *,ExceptionInfo *), *ResizeImage(const Image *,const unsigned long,const unsigned long, const FilterTypes,const double,ExceptionInfo *), *SampleImage(const Image *,const unsigned long,const unsigned long, ExceptionInfo *), *ScaleImage(const Image *,const unsigned long,const unsigned long, ExceptionInfo *), *ThumbnailImage(const Image *,const unsigned long,const unsigned long, ExceptionInfo *), *ZoomImage(const Image *,const unsigned long,const unsigned long, ExceptionInfo *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_RESIZE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/resource.h ================================================ /* Copyright (C) 2003 - 2015 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Resource methods. */ #ifndef _MAGICK_RESOURCE_H #define _MAGICK_RESOURCE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Typedef declarations. */ typedef enum { UndefinedResource=0, /* Undefined value */ DiskResource, /* Pixel cache total disk space (Gigabytes) */ FileResource, /* Pixel cache number of open files (Files) */ MapResource, /* Pixel cache total file memory-mapping (Megabytes) */ MemoryResource, /* Maximum pixel cache heap memory allocations (Megabytes) */ PixelsResource, /* Maximum number of pixels in single image (Pixels) */ ThreadsResource, /* Maximum number of worker threads */ WidthResource, /* Maximum pixel width of an image (Pixels) */ HeightResource /* Maximum pixel height of an image (Pixels) */ } ResourceType; /* Method declarations. */ extern MagickExport MagickPassFail AcquireMagickResource(const ResourceType type,const magick_uint64_t size), ListMagickResourceInfo(FILE *file,ExceptionInfo *exception), SetMagickResourceLimit(const ResourceType type,const magick_int64_t limit); extern MagickExport magick_int64_t GetMagickResource(const ResourceType type), GetMagickResourceLimit(const ResourceType type); extern MagickExport void DestroyMagickResources(void), InitializeMagickResources(void), LiberateMagickResource(const ResourceType type,const magick_uint64_t size); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/shear.h ================================================ /* Copyright (C) 2003-2012 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Shear Methods. */ #ifndef _MAGICK_SHEAR_H #define _MAGICK_SHEAR_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *AffineTransformImage(const Image *,const AffineMatrix *,ExceptionInfo *), *AutoOrientImage(const Image *image,const OrientationType current_orientation, ExceptionInfo *exception), *RotateImage(const Image *,const double,ExceptionInfo *), *ShearImage(const Image *,const double,const double,ExceptionInfo *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_SHEAR_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/signature.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Digital signature methods. */ #ifndef _MAGICK_SIGNATURE_H #define _MAGICK_SIGNATURE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Define declarations. */ #define SignatureSize 64 /* Typedef declarations. */ typedef struct _SignatureInfo { unsigned long digest[8], low_order, high_order; long offset; unsigned char message[SignatureSize]; } SignatureInfo; /* Method declarations. */ extern MagickExport unsigned int SignatureImage(Image *); extern MagickExport void FinalizeSignature(SignatureInfo *), GetSignatureInfo(SignatureInfo *), TransformSignature(SignatureInfo *), UpdateSignature(SignatureInfo *,const unsigned char *,const size_t); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/statistics.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Image Statistics Methods. */ #ifndef _MAGICK_STATISTICS_H #define _MAGICK_STATISTICS_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" typedef struct _ImageChannelStatistics { /* Minimum value observed */ double maximum; /* Maximum value observed */ double minimum; /* Average (mean) value observed */ double mean; /* Standard deviation, sqrt(variance) */ double standard_deviation; /* Variance */ double variance; } ImageChannelStatistics; typedef struct _ImageStatistics { ImageChannelStatistics red; ImageChannelStatistics green; ImageChannelStatistics blue; ImageChannelStatistics opacity; } ImageStatistics; extern MagickExport MagickPassFail GetImageStatistics(const Image *image,ImageStatistics *statistics, ExceptionInfo *exception); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_STATISTICS_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/symbols.h ================================================ /* Copyright (C) 2012-2018 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Library symbol name-scoping support. */ #if !defined(_MAGICK_SYMBOLS_H) #define _MAGICK_SYMBOLS_H #if defined(PREFIX_MAGICK_SYMBOLS) #define AccessCacheViewPixels GmAccessCacheViewPixels #define AccessDefaultCacheView GmAccessDefaultCacheView #define AccessDefinition GmAccessDefinition #define AccessImmutableIndexes GmAccessImmutableIndexes #define AccessMutableIndexes GmAccessMutableIndexes #define AccessMutablePixels GmAccessMutablePixels #define AccessThreadViewData GmAccessThreadViewData #define AccessThreadViewDataById GmAccessThreadViewDataById #define AcquireCacheView GmAcquireCacheView #define AcquireCacheViewIndexes GmAcquireCacheViewIndexes #define AcquireCacheViewPixels GmAcquireCacheViewPixels #define AcquireImagePixels GmAcquireImagePixels #define AcquireMagickRandomKernel GmAcquireMagickRandomKernel #define AcquireMagickResource GmAcquireMagickResource #define AcquireMemory GmAcquireMemory #define AcquireOneCacheViewPixel GmAcquireOneCacheViewPixel #define AcquireOnePixel GmAcquireOnePixel #define AcquireOnePixelByReference GmAcquireOnePixelByReference #define AcquireSemaphoreInfo GmAcquireSemaphoreInfo #define AcquireString GmAcquireString #define AcquireTemporaryFileDescriptor GmAcquireTemporaryFileDescriptor #define AcquireTemporaryFileName GmAcquireTemporaryFileName #define AcquireTemporaryFileStream GmAcquireTemporaryFileStream #define AdaptiveThresholdImage GmAdaptiveThresholdImage #define AddDefinition GmAddDefinition #define AddDefinitions GmAddDefinitions #define AddNoiseImage GmAddNoiseImage #define AddNoiseImageChannel GmAddNoiseImageChannel #define AffineTransformImage GmAffineTransformImage #define AllocateImage GmAllocateImage #define AllocateImageColormap GmAllocateImageColormap #define AllocateImageProfileIterator GmAllocateImageProfileIterator #define AllocateNextImage GmAllocateNextImage #define AllocateSemaphoreInfo GmAllocateSemaphoreInfo #define AllocateString GmAllocateString #define AllocateThreadViewDataArray GmAllocateThreadViewDataArray #define AllocateThreadViewDataSet GmAllocateThreadViewDataSet #define AllocateThreadViewSet GmAllocateThreadViewSet #define AnalyzeImage GmAnalyzeImage #define AnimateImageCommand GmAnimateImageCommand #define AnimateImages GmAnimateImages #define AnnotateImage GmAnnotateImage #define AppendImageFormat GmAppendImageFormat #define AppendImageProfile GmAppendImageProfile #define AppendImageToList GmAppendImageToList #define AppendImages GmAppendImages #define Ascii85Encode GmAscii85Encode #define Ascii85Flush GmAscii85Flush #define Ascii85Initialize GmAscii85Initialize #define Ascii85WriteByteHook GmAscii85WriteByteHook #define AssignThreadViewData GmAssignThreadViewData #define AttachBlob GmAttachBlob #define AutoOrientImage GmAutoOrientImage #define AverageImages GmAverageImages #define Base64Decode GmBase64Decode #define Base64Encode GmBase64Encode #define BenchmarkImageCommand GmBenchmarkImageCommand #define BlackThresholdImage GmBlackThresholdImage #define BlobIsSeekable GmBlobIsSeekable #define BlobModeToString GmBlobModeToString #define BlobReserveSize GmBlobReserveSize #define BlobToFile GmBlobToFile #define BlobToImage GmBlobToImage #define BlobWriteByteHook GmBlobWriteByteHook #define BlurImage GmBlurImage #define BlurImageChannel GmBlurImageChannel #define BorderImage GmBorderImage #define CatchException GmCatchException #define CatchImageException GmCatchImageException #define CdlImage GmCdlImage #define ChannelImage GmChannelImage #define ChannelThresholdImage GmChannelThresholdImage #define ChannelTypeToString GmChannelTypeToString #define CharcoalImage GmCharcoalImage #define CheckImagePixelLimits GmCheckImagePixelLimits #define ChopImage GmChopImage #define ClassTypeToString GmClassTypeToString #define ClipImage GmClipImage #define ClipPathImage GmClipPathImage #define CloneBlobInfo GmCloneBlobInfo #define CloneDrawInfo GmCloneDrawInfo #define CloneImage GmCloneImage #define CloneImageAttributes GmCloneImageAttributes #define CloneImageInfo GmCloneImageInfo #define CloneImageList GmCloneImageList #define CloneMemory GmCloneMemory #define CloneMontageInfo GmCloneMontageInfo #define CloneQuantizeInfo GmCloneQuantizeInfo #define CloneString GmCloneString #define CloseBlob GmCloseBlob #define CloseCacheView GmCloseCacheView #define CoalesceImages GmCoalesceImages #define ColorFloodfillImage GmColorFloodfillImage #define ColorMatrixImage GmColorMatrixImage #define ColorizeImage GmColorizeImage #define ColorspaceTypeToString GmColorspaceTypeToString #define CompareImageCommand GmCompareImageCommand #define CompositeImage GmCompositeImage #define CompositeImageCommand GmCompositeImageCommand #define CompositeImageRegion GmCompositeImageRegion #define CompositeMaskImage GmCompositeMaskImage #define CompositeOperatorToString GmCompositeOperatorToString #define CompositePathImage GmCompositePathImage #define CompressImageColormap GmCompressImageColormap #define CompressionTypeToString GmCompressionTypeToString #define ConcatenateString GmConcatenateString #define ConfirmAccessModeToString GmConfirmAccessModeToString #define ConjureImageCommand GmConjureImageCommand #define ConstituteImage GmConstituteImage #define ConstituteTextureImage GmConstituteTextureImage #define ContinueTimer GmContinueTimer #define Contrast GmContrast #define ContrastImage GmContrastImage #define ConvertImageCommand GmConvertImageCommand #define ConvolveImage GmConvolveImage #define CopyException GmCopyException #define CropImage GmCropImage #define CycleColormapImage GmCycleColormapImage #define DeallocateImageProfileIterator GmDeallocateImageProfileIterator #define DeconstructImages GmDeconstructImages #define DefineClientName GmDefineClientName #define DefineClientPathAndName GmDefineClientPathAndName #define DeleteImageFromList GmDeleteImageFromList #define DeleteImageProfile GmDeleteImageProfile #define DeleteMagickRegistry GmDeleteMagickRegistry #define DescribeImage GmDescribeImage #define DespeckleImage GmDespeckleImage #define DestroyBlob GmDestroyBlob #define DestroyBlobInfo GmDestroyBlobInfo #define DestroyCacheInfo GmDestroyCacheInfo #define DestroyColorInfo GmDestroyColorInfo #define DestroyConstitute GmDestroyConstitute #define DestroyDelegateInfo GmDestroyDelegateInfo #define DestroyDrawInfo GmDestroyDrawInfo #define DestroyExceptionInfo GmDestroyExceptionInfo #define DestroyImage GmDestroyImage #define DestroyImageAttributes GmDestroyImageAttributes #define DestroyImageInfo GmDestroyImageInfo #define DestroyImageList GmDestroyImageList #define DestroyImagePixels GmDestroyImagePixels #define DestroyLogInfo GmDestroyLogInfo #define DestroyMagicInfo GmDestroyMagicInfo #define DestroyMagick GmDestroyMagick #define DestroyMagickExceptionHandling GmDestroyMagickExceptionHandling #define DestroyMagickModules GmDestroyMagickModules #define DestroyMagickMonitor GmDestroyMagickMonitor #define DestroyMagickRandomGenerator GmDestroyMagickRandomGenerator #define DestroyMagickRegistry GmDestroyMagickRegistry #define DestroyMagickResources GmDestroyMagickResources #define DestroyMontageInfo GmDestroyMontageInfo #define DestroyQuantizeInfo GmDestroyQuantizeInfo #define DestroySemaphore GmDestroySemaphore #define DestroySemaphoreInfo GmDestroySemaphoreInfo #define DestroyTemporaryFiles GmDestroyTemporaryFiles #define DestroyThreadViewDataSet GmDestroyThreadViewDataSet #define DestroyThreadViewSet GmDestroyThreadViewSet #define DestroyTypeInfo GmDestroyTypeInfo #define DetachBlob GmDetachBlob #define DifferenceImage GmDifferenceImage #define DisassociateBlob GmDisassociateBlob #define DispatchImage GmDispatchImage #define DisplayImageCommand GmDisplayImageCommand #define DisplayImages GmDisplayImages #define DrawAffine GmDrawAffine #define DrawAffineImage GmDrawAffineImage #define DrawAllocateContext GmDrawAllocateContext #define DrawAnnotation GmDrawAnnotation #define DrawArc GmDrawArc #define DrawBezier GmDrawBezier #define DrawCircle GmDrawCircle #define DrawClipPath GmDrawClipPath #define DrawColor GmDrawColor #define DrawComment GmDrawComment #define DrawComposite GmDrawComposite #define DrawCompositeMask GmDrawCompositeMask #define DrawDestroyContext GmDrawDestroyContext #define DrawEllipse GmDrawEllipse #define DrawGetClipPath GmDrawGetClipPath #define DrawGetClipRule GmDrawGetClipRule #define DrawGetClipUnits GmDrawGetClipUnits #define DrawGetFillColor GmDrawGetFillColor #define DrawGetFillOpacity GmDrawGetFillOpacity #define DrawGetFillRule GmDrawGetFillRule #define DrawGetFont GmDrawGetFont #define DrawGetFontFamily GmDrawGetFontFamily #define DrawGetFontSize GmDrawGetFontSize #define DrawGetFontStretch GmDrawGetFontStretch #define DrawGetFontStyle GmDrawGetFontStyle #define DrawGetFontWeight GmDrawGetFontWeight #define DrawGetGravity GmDrawGetGravity #define DrawGetStrokeAntialias GmDrawGetStrokeAntialias #define DrawGetStrokeColor GmDrawGetStrokeColor #define DrawGetStrokeDashArray GmDrawGetStrokeDashArray #define DrawGetStrokeDashOffset GmDrawGetStrokeDashOffset #define DrawGetStrokeLineCap GmDrawGetStrokeLineCap #define DrawGetStrokeLineJoin GmDrawGetStrokeLineJoin #define DrawGetStrokeMiterLimit GmDrawGetStrokeMiterLimit #define DrawGetStrokeOpacity GmDrawGetStrokeOpacity #define DrawGetStrokeWidth GmDrawGetStrokeWidth #define DrawGetTextAntialias GmDrawGetTextAntialias #define DrawGetTextDecoration GmDrawGetTextDecoration #define DrawGetTextEncoding GmDrawGetTextEncoding #define DrawGetTextUnderColor GmDrawGetTextUnderColor #define DrawImage GmDrawImage #define DrawInfoGetClipPath GmDrawInfoGetClipPath #define DrawInfoGetCompositePath GmDrawInfoGetCompositePath #define DrawLine GmDrawLine #define DrawMatte GmDrawMatte #define DrawPathClose GmDrawPathClose #define DrawPathCurveToAbsolute GmDrawPathCurveToAbsolute #define DrawPathCurveToQuadraticBezierAbsolute GmDrawPathCurveToQuadraticBezierAbsolute #define DrawPathCurveToQuadraticBezierRelative GmDrawPathCurveToQuadraticBezierRelative #define DrawPathCurveToQuadraticBezierSmoothAbsolute GmDrawPathCurveToQuadraticBezierSmoothAbsolute #define DrawPathCurveToQuadraticBezierSmoothRelative GmDrawPathCurveToQuadraticBezierSmoothRelative #define DrawPathCurveToRelative GmDrawPathCurveToRelative #define DrawPathCurveToSmoothAbsolute GmDrawPathCurveToSmoothAbsolute #define DrawPathCurveToSmoothRelative GmDrawPathCurveToSmoothRelative #define DrawPathEllipticArcAbsolute GmDrawPathEllipticArcAbsolute #define DrawPathEllipticArcRelative GmDrawPathEllipticArcRelative #define DrawPathFinish GmDrawPathFinish #define DrawPathLineToAbsolute GmDrawPathLineToAbsolute #define DrawPathLineToHorizontalAbsolute GmDrawPathLineToHorizontalAbsolute #define DrawPathLineToHorizontalRelative GmDrawPathLineToHorizontalRelative #define DrawPathLineToRelative GmDrawPathLineToRelative #define DrawPathLineToVerticalAbsolute GmDrawPathLineToVerticalAbsolute #define DrawPathLineToVerticalRelative GmDrawPathLineToVerticalRelative #define DrawPathMoveToAbsolute GmDrawPathMoveToAbsolute #define DrawPathMoveToRelative GmDrawPathMoveToRelative #define DrawPathStart GmDrawPathStart #define DrawPatternPath GmDrawPatternPath #define DrawPeekGraphicContext GmDrawPeekGraphicContext #define DrawPoint GmDrawPoint #define DrawPolygon GmDrawPolygon #define DrawPolyline GmDrawPolyline #define DrawPopClipPath GmDrawPopClipPath #define DrawPopDefs GmDrawPopDefs #define DrawPopGraphicContext GmDrawPopGraphicContext #define DrawPopPattern GmDrawPopPattern #define DrawPushClipPath GmDrawPushClipPath #define DrawPushDefs GmDrawPushDefs #define DrawPushGraphicContext GmDrawPushGraphicContext #define DrawPushPattern GmDrawPushPattern #define DrawRectangle GmDrawRectangle #define DrawRender GmDrawRender #define DrawRotate GmDrawRotate #define DrawRoundRectangle GmDrawRoundRectangle #define DrawScale GmDrawScale #define DrawSetClipPath GmDrawSetClipPath #define DrawSetClipRule GmDrawSetClipRule #define DrawSetClipUnits GmDrawSetClipUnits #define DrawSetFillColor GmDrawSetFillColor #define DrawSetFillColorString GmDrawSetFillColorString #define DrawSetFillOpacity GmDrawSetFillOpacity #define DrawSetFillPatternURL GmDrawSetFillPatternURL #define DrawSetFillRule GmDrawSetFillRule #define DrawSetFont GmDrawSetFont #define DrawSetFontFamily GmDrawSetFontFamily #define DrawSetFontSize GmDrawSetFontSize #define DrawSetFontStretch GmDrawSetFontStretch #define DrawSetFontStyle GmDrawSetFontStyle #define DrawSetFontWeight GmDrawSetFontWeight #define DrawSetGravity GmDrawSetGravity #define DrawSetStrokeAntialias GmDrawSetStrokeAntialias #define DrawSetStrokeColor GmDrawSetStrokeColor #define DrawSetStrokeColorString GmDrawSetStrokeColorString #define DrawSetStrokeDashArray GmDrawSetStrokeDashArray #define DrawSetStrokeDashOffset GmDrawSetStrokeDashOffset #define DrawSetStrokeLineCap GmDrawSetStrokeLineCap #define DrawSetStrokeLineJoin GmDrawSetStrokeLineJoin #define DrawSetStrokeMiterLimit GmDrawSetStrokeMiterLimit #define DrawSetStrokeOpacity GmDrawSetStrokeOpacity #define DrawSetStrokePatternURL GmDrawSetStrokePatternURL #define DrawSetStrokeWidth GmDrawSetStrokeWidth #define DrawSetTextAntialias GmDrawSetTextAntialias #define DrawSetTextDecoration GmDrawSetTextDecoration #define DrawSetTextEncoding GmDrawSetTextEncoding #define DrawSetTextUnderColor GmDrawSetTextUnderColor #define DrawSetTextUnderColorString GmDrawSetTextUnderColorString #define DrawSetViewbox GmDrawSetViewbox #define DrawSkewX GmDrawSkewX #define DrawSkewY GmDrawSkewY #define DrawTranslate GmDrawTranslate #define EOFBlob GmEOFBlob #define EdgeImage GmEdgeImage #define EmbossImage GmEmbossImage #define EndianTypeToString GmEndianTypeToString #define EnhanceImage GmEnhanceImage #define EqualizeImage GmEqualizeImage #define EscapeString GmEscapeString #define ExecuteModuleProcess GmExecuteModuleProcess #define ExpandAffine GmExpandAffine #define ExpandFilename GmExpandFilename #define ExpandFilenames GmExpandFilenames #define ExportImageChannel GmExportImageChannel #define ExportImagePixelArea GmExportImagePixelArea #define ExportPixelAreaOptionsInit GmExportPixelAreaOptionsInit #define ExportViewPixelArea GmExportViewPixelArea #define ExtentImage GmExtentImage #define FileToBlob GmFileToBlob #define FinalizeSignature GmFinalizeSignature #define FlattenImages GmFlattenImages #define FlipImage GmFlipImage #define FlopImage GmFlopImage #define FormatSize GmFormatSize #define FormatString GmFormatString #define FormatStringList GmFormatStringList #define FrameImage GmFrameImage #define FuzzyColorMatch GmFuzzyColorMatch #define GammaImage GmGammaImage #define GaussianBlurImage GmGaussianBlurImage #define GaussianBlurImageChannel GmGaussianBlurImageChannel #define GenerateDifferentialNoise GmGenerateDifferentialNoise #define GenerateNoise GmGenerateNoise #define GetBlobFileHandle GmGetBlobFileHandle #define GetBlobFirstErrno GmGetBlobFirstErrno #define GetBlobInfo GmGetBlobInfo #define GetBlobIsOpen GmGetBlobIsOpen #define GetBlobSize GmGetBlobSize #define GetBlobStatus GmGetBlobStatus #define GetBlobStreamData GmGetBlobStreamData #define GetBlobTemporary GmGetBlobTemporary #define GetCacheInfo GmGetCacheInfo #define GetCacheView GmGetCacheView #define GetCacheViewArea GmGetCacheViewArea #define GetCacheViewImage GmGetCacheViewImage #define GetCacheViewIndexes GmGetCacheViewIndexes #define GetCacheViewPixels GmGetCacheViewPixels #define GetCacheViewRegion GmGetCacheViewRegion #define GetClientFilename GmGetClientFilename #define GetClientName GmGetClientName #define GetClientPath GmGetClientPath #define GetColorHistogram GmGetColorHistogram #define GetColorInfo GmGetColorInfo #define GetColorInfoArray GmGetColorInfoArray #define GetColorList GmGetColorList #define GetColorTuple GmGetColorTuple #define GetConfigureBlob GmGetConfigureBlob #define GetDelegateCommand GmGetDelegateCommand #define GetDelegateInfo GmGetDelegateInfo #define GetDrawInfo GmGetDrawInfo #define GetElapsedTime GmGetElapsedTime #define GetExceptionInfo GmGetExceptionInfo #define GetExecutionPath GmGetExecutionPath #define GetExecutionPathUsingName GmGetExecutionPathUsingName #define GetFirstImageInList GmGetFirstImageInList #define GetGeometry GmGetGeometry #define GetImageAttribute GmGetImageAttribute #define GetImageBoundingBox GmGetImageBoundingBox #define GetImageChannelDepth GmGetImageChannelDepth #define GetImageChannelDifference GmGetImageChannelDifference #define GetImageChannelDistortion GmGetImageChannelDistortion #define GetImageCharacteristics GmGetImageCharacteristics #define GetImageClipMask GmGetImageClipMask #define GetImageClippingPathAttribute GmGetImageClippingPathAttribute #define GetImageCompositeMask GmGetImageCompositeMask #define GetImageDepth GmGetImageDepth #define GetImageDistortion GmGetImageDistortion #define GetImageException GmGetImageException #define GetImageFromList GmGetImageFromList #define GetImageFromMagickRegistry GmGetImageFromMagickRegistry #define GetImageGeometry GmGetImageGeometry #define GetImageIndexInList GmGetImageIndexInList #define GetImageInfo GmGetImageInfo #define GetImageInfoAttribute GmGetImageInfoAttribute #define GetImageListLength GmGetImageListLength #define GetImageMagick GmGetImageMagick #define GetImagePixels GmGetImagePixels #define GetImagePixelsEx GmGetImagePixelsEx #define GetImageProfile GmGetImageProfile #define GetImageQuantizeError GmGetImageQuantizeError #define GetImageStatistics GmGetImageStatistics #define GetImageType GmGetImageType #define GetImageVirtualPixelMethod GmGetImageVirtualPixelMethod #define GetIndexes GmGetIndexes #define GetLastImageInList GmGetLastImageInList #define GetLocaleExceptionMessage GmGetLocaleExceptionMessage #define GetLocaleMessage GmGetLocaleMessage #define GetLocaleMessageFromID GmGetLocaleMessageFromID #define GetMagickCopyright GmGetMagickCopyright #define GetMagickDimension GmGetMagickDimension #define GetMagickFileFormat GmGetMagickFileFormat #define GetMagickGeometry GmGetMagickGeometry #define GetMagickInfo GmGetMagickInfo #define GetMagickInfoArray GmGetMagickInfoArray #define GetMagickRegistry GmGetMagickRegistry #define GetMagickResource GmGetMagickResource #define GetMagickResourceLimit GmGetMagickResourceLimit #define GetMagickVersion GmGetMagickVersion #define GetMagickWebSite GmGetMagickWebSite #define GetMontageInfo GmGetMontageInfo #define GetNextImageInList GmGetNextImageInList #define GetNumberColors GmGetNumberColors #define GetOnePixel GmGetOnePixel #define GetOptimalKernelWidth GmGetOptimalKernelWidth #define GetOptimalKernelWidth1D GmGetOptimalKernelWidth1D #define GetOptimalKernelWidth2D GmGetOptimalKernelWidth2D #define GetPageGeometry GmGetPageGeometry #define GetPathComponent GmGetPathComponent #define GetPixelCacheArea GmGetPixelCacheArea #define GetPixelCacheInCore GmGetPixelCacheInCore #define GetPixelCachePresent GmGetPixelCachePresent #define GetPixels GmGetPixels #define GetPostscriptDelegateInfo GmGetPostscriptDelegateInfo #define GetPreviousImageInList GmGetPreviousImageInList #define GetQuantizeInfo GmGetQuantizeInfo #define GetSignatureInfo GmGetSignatureInfo #define GetThreadViewDataSetAllocatedViews GmGetThreadViewDataSetAllocatedViews #define GetTimerInfo GmGetTimerInfo #define GetTimerResolution GmGetTimerResolution #define GetToken GmGetToken #define GetTypeInfo GmGetTypeInfo #define GetTypeInfoByFamily GmGetTypeInfoByFamily #define GetTypeList GmGetTypeList #define GetTypeMetrics GmGetTypeMetrics #define GetUserTime GmGetUserTime #define GlobExpression GmGlobExpression #define GradientImage GmGradientImage #define GravityTypeToString GmGravityTypeToString #define GrayscalePseudoClassImage GmGrayscalePseudoClassImage #define HSLTransform GmHSLTransform #define HWBTransform GmHWBTransform #define HaldClutImage GmHaldClutImage #define HighlightStyleToString GmHighlightStyleToString #define HuffmanDecodeImage GmHuffmanDecodeImage #define HuffmanEncode2Image GmHuffmanEncode2Image #define HuffmanEncodeImage GmHuffmanEncodeImage #define Hull GmHull #define IdentifyImageCommand GmIdentifyImageCommand #define IdentityAffine GmIdentityAffine #define ImageGetClipMask GmImageGetClipMask #define ImageGetCompositeMask GmImageGetCompositeMask #define ImageListToArray GmImageListToArray #define ImageToBlob GmImageToBlob #define ImageToFile GmImageToFile #define ImageToHuffman2DBlob GmImageToHuffman2DBlob #define ImageToJPEGBlob GmImageToJPEGBlob #define ImageTypeToString GmImageTypeToString #define ImplodeImage GmImplodeImage #define ImportImageChannel GmImportImageChannel #define ImportImageChannelsMasked GmImportImageChannelsMasked #define ImportImageCommand GmImportImageCommand #define ImportImagePixelArea GmImportImagePixelArea #define ImportPixelAreaOptionsInit GmImportPixelAreaOptionsInit #define ImportViewPixelArea GmImportViewPixelArea #define InitializeColorInfo GmInitializeColorInfo #define InitializeConstitute GmInitializeConstitute #define InitializeDelegateInfo GmInitializeDelegateInfo #define InitializeDifferenceImageOptions GmInitializeDifferenceImageOptions #define InitializeDifferenceStatistics GmInitializeDifferenceStatistics #define InitializeLogInfo GmInitializeLogInfo #define InitializeLogInfoPost GmInitializeLogInfoPost #define InitializeMagicInfo GmInitializeMagicInfo #define InitializeMagick GmInitializeMagick #define InitializeMagickEx GmInitializeMagickEx #define InitializeMagickExceptionHandling GmInitializeMagickExceptionHandling #define InitializeMagickModules GmInitializeMagickModules #define InitializeMagickMonitor GmInitializeMagickMonitor #define InitializeMagickRandomGenerator GmInitializeMagickRandomGenerator #define InitializeMagickRandomKernel GmInitializeMagickRandomKernel #define InitializeMagickRegistry GmInitializeMagickRegistry #define InitializeMagickResources GmInitializeMagickResources #define InitializePixelIteratorOptions GmInitializePixelIteratorOptions #define InitializeSemaphore GmInitializeSemaphore #define InitializeTemporaryFiles GmInitializeTemporaryFiles #define InitializeTypeInfo GmInitializeTypeInfo #define InsertImageInList GmInsertImageInList #define InsertRowHDU GmInsertRowHDU #define InterlaceTypeToString GmInterlaceTypeToString #define InterpolateColor GmInterpolateColor #define InterpolateViewColor GmInterpolateViewColor #define InvokeDelegate GmInvokeDelegate #define InvokePostscriptDelegate GmInvokePostscriptDelegate #define IsAccessible GmIsAccessible #define IsAccessibleAndNotEmpty GmIsAccessibleAndNotEmpty #define IsAccessibleNoLogging GmIsAccessibleNoLogging #define IsEventLogging GmIsEventLogging #define IsGeometry GmIsGeometry #define IsGlob GmIsGlob #define IsGrayImage GmIsGrayImage #define IsImagesEqual GmIsImagesEqual #define IsMagickConflict GmIsMagickConflict #define IsMonochromeImage GmIsMonochromeImage #define IsOpaqueImage GmIsOpaqueImage #define IsPaletteImage GmIsPaletteImage #define IsSubimage GmIsSubimage #define IsTaintImage GmIsTaintImage #define IsWriteable GmIsWriteable #define LZWEncode2Image GmLZWEncode2Image #define LZWEncodeImage GmLZWEncodeImage #define LevelImage GmLevelImage #define LevelImageChannel GmLevelImageChannel #define LiberateMagickResource GmLiberateMagickResource #define LiberateMemory GmLiberateMemory #define LiberateSemaphoreInfo GmLiberateSemaphoreInfo #define LiberateTemporaryFile GmLiberateTemporaryFile #define ListColorInfo GmListColorInfo #define ListDelegateInfo GmListDelegateInfo #define ListFiles GmListFiles #define ListMagicInfo GmListMagicInfo #define ListMagickInfo GmListMagickInfo #define ListMagickResourceInfo GmListMagickResourceInfo #define ListModuleMap GmListModuleMap #define ListTypeInfo GmListTypeInfo #define LocaleCompare GmLocaleCompare #define LocaleLower GmLocaleLower #define LocaleNCompare GmLocaleNCompare #define LocaleUpper GmLocaleUpper #define LockSemaphoreInfo GmLockSemaphoreInfo #define MSBOrderLong GmMSBOrderLong #define MSBOrderShort GmMSBOrderShort #define MagickAllocFunctions GmMagickAllocFunctions #define MagickArraySize GmMagickArraySize #define MagickAtoFChk GmMagickAtoFChk #define MagickAtoIChk GmMagickAtoIChk #define MagickAtoLChk GmMagickAtoLChk #define MagickAtoUIChk GmMagickAtoUIChk #define MagickAtoULChk GmMagickAtoULChk #define MagickBitStreamInitializeRead GmMagickBitStreamInitializeRead #define MagickBitStreamInitializeWrite GmMagickBitStreamInitializeWrite #define MagickBitStreamMSBRead GmMagickBitStreamMSBRead #define MagickBitStreamMSBWrite GmMagickBitStreamMSBWrite #define MagickCloneMemory GmMagickCloneMemory #define MagickCommand GmMagickCommand #define MagickCompositeImageUnderColor GmMagickCompositeImageUnderColor #define MagickConfirmAccess GmMagickConfirmAccess #define MagickConstrainColormapIndex GmMagickConstrainColormapIndex #define MagickCreateDirectoryPath GmMagickCreateDirectoryPath #define MagickDestroyCommandInfo GmMagickDestroyCommandInfo #define MagickFindRawImageMinMax GmMagickFindRawImageMinMax #define MagickFmax GmMagickFmax #define MagickFmin GmMagickFmin #define MagickFormatString GmMagickFormatString #define MagickFormatStringList GmMagickFormatStringList #define MagickFree GmMagickFree #define MagickFreeAligned GmMagickFreeAligned #define MagickGetBitRevTable GmMagickGetBitRevTable #define MagickGetFileAttributes GmMagickGetFileAttributes #define MagickGetFileSystemBlockSize GmMagickGetFileSystemBlockSize #define MagickGetMMUPageSize GmMagickGetMMUPageSize #define MagickGetQuantumSamplesPerPixel GmMagickGetQuantumSamplesPerPixel #define MagickGetToken GmMagickGetToken #define MagickInitializeCommandInfo GmMagickInitializeCommandInfo #define MagickIsTrue GmMagickIsTrue #define MagickMalloc GmMagickMalloc #define MagickMallocAligned GmMagickMallocAligned #define MagickMallocAlignedArray GmMagickMallocAlignedArray #define MagickMallocArray GmMagickMallocArray #define MagickMallocCleared GmMagickMallocCleared #define MagickMapAccessEntry GmMagickMapAccessEntry #define MagickMapAddEntry GmMagickMapAddEntry #define MagickMapAllocateIterator GmMagickMapAllocateIterator #define MagickMapAllocateMap GmMagickMapAllocateMap #define MagickMapClearMap GmMagickMapClearMap #define MagickMapCloneMap GmMagickMapCloneMap #define MagickMapCopyBlob GmMagickMapCopyBlob #define MagickMapCopyString GmMagickMapCopyString #define MagickMapDeallocateBlob GmMagickMapDeallocateBlob #define MagickMapDeallocateIterator GmMagickMapDeallocateIterator #define MagickMapDeallocateMap GmMagickMapDeallocateMap #define MagickMapDeallocateString GmMagickMapDeallocateString #define MagickMapDereferenceIterator GmMagickMapDereferenceIterator #define MagickMapIterateNext GmMagickMapIterateNext #define MagickMapIteratePrevious GmMagickMapIteratePrevious #define MagickMapIterateToBack GmMagickMapIterateToBack #define MagickMapIterateToFront GmMagickMapIterateToFront #define MagickMapRemoveEntry GmMagickMapRemoveEntry #define MagickMonitor GmMagickMonitor #define MagickMonitorActive GmMagickMonitorActive #define MagickMonitorFormatted GmMagickMonitorFormatted #define MagickRandNewSeed GmMagickRandNewSeed #define MagickRandReentrant GmMagickRandReentrant #define MagickRandomInteger GmMagickRandomInteger #define MagickRandomReal GmMagickRandomReal #define MagickRealloc GmMagickRealloc #define MagickReverseBits GmMagickReverseBits #define MagickSceneFileName GmMagickSceneFileName #define MagickSetConfirmAccessHandler GmMagickSetConfirmAccessHandler #define MagickSetFileAttributes GmMagickSetFileAttributes #define MagickSetFileSystemBlockSize GmMagickSetFileSystemBlockSize #define MagickSizeStrToInt64 GmMagickSizeStrToInt64 #define MagickSpawnVP GmMagickSpawnVP #define MagickStripSpacesFromString GmMagickStripSpacesFromString #define MagickStrlCat GmMagickStrlCat #define MagickStrlCpy GmMagickStrlCpy #define MagickStrlCpyTrunc GmMagickStrlCpyTrunc #define MagickSwabArrayOfDouble GmMagickSwabArrayOfDouble #define MagickSwabArrayOfFloat GmMagickSwabArrayOfFloat #define MagickSwabArrayOfUInt16 GmMagickSwabArrayOfUInt16 #define MagickSwabArrayOfUInt32 GmMagickSwabArrayOfUInt32 #define MagickSwabDouble GmMagickSwabDouble #define MagickSwabFloat GmMagickSwabFloat #define MagickSwabUInt16 GmMagickSwabUInt16 #define MagickSwabUInt32 GmMagickSwabUInt32 #define MagickToMime GmMagickToMime #define MagickTsdGetSpecific GmMagickTsdGetSpecific #define MagickTsdKeyCreate GmMagickTsdKeyCreate #define MagickTsdKeyCreate2 GmMagickTsdKeyCreate2 #define MagickTsdKeyDelete GmMagickTsdKeyDelete #define MagickTsdSetSpecific GmMagickTsdSetSpecific #define MagickWordStreamInitializeRead GmMagickWordStreamInitializeRead #define MagickWordStreamInitializeWrite GmMagickWordStreamInitializeWrite #define MagickWordStreamLSBRead GmMagickWordStreamLSBRead #define MagickWordStreamLSBWrite GmMagickWordStreamLSBWrite #define MagickWordStreamLSBWriteFlush GmMagickWordStreamLSBWriteFlush #define MagickXAnimateBackgroundImage GmMagickXAnimateBackgroundImage #define MagickXAnimateImages GmMagickXAnimateImages #define MagickXAnnotateImage GmMagickXAnnotateImage #define MagickXBestFont GmMagickXBestFont #define MagickXBestIconSize GmMagickXBestIconSize #define MagickXBestPixel GmMagickXBestPixel #define MagickXBestVisualInfo GmMagickXBestVisualInfo #define MagickXCheckRefreshWindows GmMagickXCheckRefreshWindows #define MagickXClientMessage GmMagickXClientMessage #define MagickXColorBrowserWidget GmMagickXColorBrowserWidget #define MagickXCommandWidget GmMagickXCommandWidget #define MagickXConfigureImageColormap GmMagickXConfigureImageColormap #define MagickXConfirmWidget GmMagickXConfirmWidget #define MagickXConstrainWindowPosition GmMagickXConstrainWindowPosition #define MagickXDelay GmMagickXDelay #define MagickXDestroyResourceInfo GmMagickXDestroyResourceInfo #define MagickXDestroyWindowColors GmMagickXDestroyWindowColors #define MagickXDestroyX11Resources GmMagickXDestroyX11Resources #define MagickXDestroyXWindowInfo GmMagickXDestroyXWindowInfo #define MagickXDestroyXWindows GmMagickXDestroyXWindows #define MagickXDialogWidget GmMagickXDialogWidget #define MagickXDisplayBackgroundImage GmMagickXDisplayBackgroundImage #define MagickXDisplayImage GmMagickXDisplayImage #define MagickXDisplayImageInfo GmMagickXDisplayImageInfo #define MagickXDrawImage GmMagickXDrawImage #define MagickXError GmMagickXError #define MagickXFileBrowserWidget GmMagickXFileBrowserWidget #define MagickXFontBrowserWidget GmMagickXFontBrowserWidget #define MagickXFreeResources GmMagickXFreeResources #define MagickXFreeStandardColormap GmMagickXFreeStandardColormap #define MagickXGetAnnotateInfo GmMagickXGetAnnotateInfo #define MagickXGetImportInfo GmMagickXGetImportInfo #define MagickXGetMapInfo GmMagickXGetMapInfo #define MagickXGetPixelPacket GmMagickXGetPixelPacket #define MagickXGetResourceClass GmMagickXGetResourceClass #define MagickXGetResourceDatabase GmMagickXGetResourceDatabase #define MagickXGetResourceInfo GmMagickXGetResourceInfo #define MagickXGetResourceInstance GmMagickXGetResourceInstance #define MagickXGetScreenDensity GmMagickXGetScreenDensity #define MagickXGetWindowColor GmMagickXGetWindowColor #define MagickXGetWindowInfo GmMagickXGetWindowInfo #define MagickXHighlightEllipse GmMagickXHighlightEllipse #define MagickXHighlightLine GmMagickXHighlightLine #define MagickXHighlightRectangle GmMagickXHighlightRectangle #define MagickXImportImage GmMagickXImportImage #define MagickXInfoWidget GmMagickXInfoWidget #define MagickXInitializeWindows GmMagickXInitializeWindows #define MagickXListBrowserWidget GmMagickXListBrowserWidget #define MagickXMagickMonitor GmMagickXMagickMonitor #define MagickXMakeCursor GmMagickXMakeCursor #define MagickXMakeImage GmMagickXMakeImage #define MagickXMakeMagnifyImage GmMagickXMakeMagnifyImage #define MagickXMakeStandardColormap GmMagickXMakeStandardColormap #define MagickXMakeWindow GmMagickXMakeWindow #define MagickXMenuWidget GmMagickXMenuWidget #define MagickXMonitorWidget GmMagickXMonitorWidget #define MagickXNoticeWidget GmMagickXNoticeWidget #define MagickXPreferencesWidget GmMagickXPreferencesWidget #define MagickXQueryColorDatabase GmMagickXQueryColorDatabase #define MagickXQueryPosition GmMagickXQueryPosition #define MagickXRefreshWindow GmMagickXRefreshWindow #define MagickXRemoteCommand GmMagickXRemoteCommand #define MagickXRetainWindowColors GmMagickXRetainWindowColors #define MagickXSetCursorState GmMagickXSetCursorState #define MagickXSetWindows GmMagickXSetWindows #define MagickXSignalHandler GmMagickXSignalHandler #define MagickXTextViewWidget GmMagickXTextViewWidget #define MagickXTextViewWidgetNDL GmMagickXTextViewWidgetNDL #define MagickXUserPreferences GmMagickXUserPreferences #define MagickXWarning GmMagickXWarning #define MagickXWindowByID GmMagickXWindowByID #define MagickXWindowByName GmMagickXWindowByName #define MagickXWindowByProperty GmMagickXWindowByProperty #define MagnifyImage GmMagnifyImage #define MapBlob GmMapBlob #define MapImage GmMapImage #define MapImages GmMapImages #define MapModeToString GmMapModeToString #define MatteFloodfillImage GmMatteFloodfillImage #define MedianFilterImage GmMedianFilterImage #define MetricTypeToString GmMetricTypeToString #define MinifyImage GmMinifyImage #define ModifyCache GmModifyCache #define ModifyImage GmModifyImage #define Modulate GmModulate #define ModulateImage GmModulateImage #define MogrifyImage GmMogrifyImage #define MogrifyImageCommand GmMogrifyImageCommand #define MogrifyImages GmMogrifyImages #define MontageImageCommand GmMontageImageCommand #define MontageImages GmMontageImages #define MorphImages GmMorphImages #define MosaicImages GmMosaicImages #define MotionBlurImage GmMotionBlurImage #define MultilineCensus GmMultilineCensus #define NegateImage GmNegateImage #define NewImageList GmNewImageList #define NextImageProfile GmNextImageProfile #define NoiseTypeToString GmNoiseTypeToString #define NormalizeImage GmNormalizeImage #define OilPaintImage GmOilPaintImage #define OpaqueImage GmOpaqueImage #define OpenBlob GmOpenBlob #define OpenCacheView GmOpenCacheView #define OpenModule GmOpenModule #define OpenModules GmOpenModules #define OrderedDitherImage GmOrderedDitherImage #define OrientationTypeToString GmOrientationTypeToString #define PackbitsEncode2Image GmPackbitsEncode2Image #define PackbitsEncodeImage GmPackbitsEncodeImage #define PanicDestroyMagick GmPanicDestroyMagick #define PersistCache GmPersistCache #define PingBlob GmPingBlob #define PingImage GmPingImage #define PixelIterateDualModify GmPixelIterateDualModify #define PixelIterateDualNew GmPixelIterateDualNew #define PixelIterateDualRead GmPixelIterateDualRead #define PixelIterateMonoModify GmPixelIterateMonoModify #define PixelIterateMonoRead GmPixelIterateMonoRead #define PixelIterateMonoSet GmPixelIterateMonoSet #define PixelIterateTripleModify GmPixelIterateTripleModify #define PixelIterateTripleNew GmPixelIterateTripleNew #define PlasmaImage GmPlasmaImage #define PopImagePixels GmPopImagePixels #define PrependImageToList GmPrependImageToList #define ProfileImage GmProfileImage #define PurgeTemporaryFiles GmPurgeTemporaryFiles #define PurgeTemporaryFilesAsyncSafe GmPurgeTemporaryFilesAsyncSafe #define PushImagePixels GmPushImagePixels #define QuantizeImage GmQuantizeImage #define QuantizeImages GmQuantizeImages #define QuantumOperatorImage GmQuantumOperatorImage #define QuantumOperatorImageMultivalue GmQuantumOperatorImageMultivalue #define QuantumOperatorRegionImage GmQuantumOperatorRegionImage #define QuantumOperatorToString GmQuantumOperatorToString #define QuantumSampleTypeToString GmQuantumSampleTypeToString #define QuantumTypeToString GmQuantumTypeToString #define QueryColorDatabase GmQueryColorDatabase #define QueryColorname GmQueryColorname #define RGBTransformImage GmRGBTransformImage #define RaiseImage GmRaiseImage #define RandomChannelThresholdImage GmRandomChannelThresholdImage #define ReacquireMemory GmReacquireMemory #define ReadBlob GmReadBlob #define ReadBlobByte GmReadBlobByte #define ReadBlobLSBDouble GmReadBlobLSBDouble #define ReadBlobLSBDoubles GmReadBlobLSBDoubles #define ReadBlobLSBFloat GmReadBlobLSBFloat #define ReadBlobLSBFloats GmReadBlobLSBFloats #define ReadBlobLSBLong GmReadBlobLSBLong #define ReadBlobLSBLongs GmReadBlobLSBLongs #define ReadBlobLSBShort GmReadBlobLSBShort #define ReadBlobLSBShorts GmReadBlobLSBShorts #define ReadBlobLSBSignedLong GmReadBlobLSBSignedLong #define ReadBlobLSBSignedShort GmReadBlobLSBSignedShort #define ReadBlobMSBDouble GmReadBlobMSBDouble #define ReadBlobMSBDoubles GmReadBlobMSBDoubles #define ReadBlobMSBFloat GmReadBlobMSBFloat #define ReadBlobMSBFloats GmReadBlobMSBFloats #define ReadBlobMSBLong GmReadBlobMSBLong #define ReadBlobMSBLongs GmReadBlobMSBLongs #define ReadBlobMSBShort GmReadBlobMSBShort #define ReadBlobMSBShorts GmReadBlobMSBShorts #define ReadBlobMSBSignedLong GmReadBlobMSBSignedLong #define ReadBlobMSBSignedShort GmReadBlobMSBSignedShort #define ReadBlobString GmReadBlobString #define ReadBlobZC GmReadBlobZC #define ReadImage GmReadImage #define ReadInlineImage GmReadInlineImage #define ReallocateImageColormap GmReallocateImageColormap #define ReduceNoiseImage GmReduceNoiseImage #define ReferenceBlob GmReferenceBlob #define ReferenceCache GmReferenceCache #define ReferenceImage GmReferenceImage #define RegisterARTImage GmRegisterARTImage #define RegisterAVSImage GmRegisterAVSImage #define RegisterBMPImage GmRegisterBMPImage #define RegisterBRAILLEImage GmRegisterBRAILLEImage #define RegisterCALSImage GmRegisterCALSImage #define RegisterCAPTIONImage GmRegisterCAPTIONImage #define RegisterCINEONImage GmRegisterCINEONImage #define RegisterCMYKImage GmRegisterCMYKImage #define RegisterCUTImage GmRegisterCUTImage #define RegisterDCMImage GmRegisterDCMImage #define RegisterDCRAWImage GmRegisterDCRAWImage #define RegisterDIBImage GmRegisterDIBImage #define RegisterDPXImage GmRegisterDPXImage #define RegisterEPTImage GmRegisterEPTImage #define RegisterFAXImage GmRegisterFAXImage #define RegisterFITSImage GmRegisterFITSImage #define RegisterGIFImage GmRegisterGIFImage #define RegisterGRADIENTImage GmRegisterGRADIENTImage #define RegisterGRAYImage GmRegisterGRAYImage #define RegisterHISTOGRAMImage GmRegisterHISTOGRAMImage #define RegisterHRZImage GmRegisterHRZImage #define RegisterHTMLImage GmRegisterHTMLImage #define RegisterICONImage GmRegisterICONImage #define RegisterIDENTITYImage GmRegisterIDENTITYImage #define RegisterINFOImage GmRegisterINFOImage #define RegisterJNXImage GmRegisterJNXImage #define RegisterJP2Image GmRegisterJP2Image #define RegisterJPEGImage GmRegisterJPEGImage #define RegisterLABELImage GmRegisterLABELImage #define RegisterLOCALEImage GmRegisterLOCALEImage #define RegisterLOGOImage GmRegisterLOGOImage #define RegisterMACImage GmRegisterMACImage #define RegisterMAPImage GmRegisterMAPImage #define RegisterMATImage GmRegisterMATImage #define RegisterMATTEImage GmRegisterMATTEImage #define RegisterMETAImage GmRegisterMETAImage #define RegisterMIFFImage GmRegisterMIFFImage #define RegisterMONOImage GmRegisterMONOImage #define RegisterMPCImage GmRegisterMPCImage #define RegisterMPEGImage GmRegisterMPEGImage #define RegisterMPRImage GmRegisterMPRImage #define RegisterMSLImage GmRegisterMSLImage #define RegisterMTVImage GmRegisterMTVImage #define RegisterMVGImage GmRegisterMVGImage #define RegisterMagickInfo GmRegisterMagickInfo #define RegisterNULLImage GmRegisterNULLImage #define RegisterOTBImage GmRegisterOTBImage #define RegisterPALMImage GmRegisterPALMImage #define RegisterPCDImage GmRegisterPCDImage #define RegisterPCLImage GmRegisterPCLImage #define RegisterPCXImage GmRegisterPCXImage #define RegisterPDBImage GmRegisterPDBImage #define RegisterPDFImage GmRegisterPDFImage #define RegisterPICTImage GmRegisterPICTImage #define RegisterPIXImage GmRegisterPIXImage #define RegisterPLASMAImage GmRegisterPLASMAImage #define RegisterPNGImage GmRegisterPNGImage #define RegisterPNMImage GmRegisterPNMImage #define RegisterPREVIEWImage GmRegisterPREVIEWImage #define RegisterPS2Image GmRegisterPS2Image #define RegisterPS3Image GmRegisterPS3Image #define RegisterPSDImage GmRegisterPSDImage #define RegisterPSImage GmRegisterPSImage #define RegisterPWPImage GmRegisterPWPImage #define RegisterRGBImage GmRegisterRGBImage #define RegisterRLAImage GmRegisterRLAImage #define RegisterRLEImage GmRegisterRLEImage #define RegisterSCTImage GmRegisterSCTImage #define RegisterSFWImage GmRegisterSFWImage #define RegisterSGIImage GmRegisterSGIImage #define RegisterSTEGANOImage GmRegisterSTEGANOImage #define RegisterSUNImage GmRegisterSUNImage #define RegisterSVGImage GmRegisterSVGImage #define RegisterStaticModules GmRegisterStaticModules #define RegisterTGAImage GmRegisterTGAImage #define RegisterTIFFImage GmRegisterTIFFImage #define RegisterTILEImage GmRegisterTILEImage #define RegisterTIMImage GmRegisterTIMImage #define RegisterTOPOLImage GmRegisterTOPOLImage #define RegisterTTFImage GmRegisterTTFImage #define RegisterTXTImage GmRegisterTXTImage #define RegisterUILImage GmRegisterUILImage #define RegisterURLImage GmRegisterURLImage #define RegisterUYVYImage GmRegisterUYVYImage #define RegisterVICARImage GmRegisterVICARImage #define RegisterVIDImage GmRegisterVIDImage #define RegisterVIFFImage GmRegisterVIFFImage #define RegisterWBMPImage GmRegisterWBMPImage #define RegisterWEBPImage GmRegisterWEBPImage #define RegisterWMFImage GmRegisterWMFImage #define RegisterWPGImage GmRegisterWPGImage #define RegisterXBMImage GmRegisterXBMImage #define RegisterXCFImage GmRegisterXCFImage #define RegisterXCImage GmRegisterXCImage #define RegisterXImage GmRegisterXImage #define RegisterXPMImage GmRegisterXPMImage #define RegisterXWDImage GmRegisterXWDImage #define RegisterYUVImage GmRegisterYUVImage #define RemoveDefinitions GmRemoveDefinitions #define RemoveFirstImageFromList GmRemoveFirstImageFromList #define RemoveLastImageFromList GmRemoveLastImageFromList #define ReplaceImageColormap GmReplaceImageColormap #define ReplaceImageInList GmReplaceImageInList #define ResetImagePage GmResetImagePage #define ResetTimer GmResetTimer #define ResizeFilterToString GmResizeFilterToString #define ResizeImage GmResizeImage #define ResolutionTypeToString GmResolutionTypeToString #define ReverseImageList GmReverseImageList #define RollImage GmRollImage #define RotateImage GmRotateImage #define SampleImage GmSampleImage #define ScaleImage GmScaleImage #define SeekBlob GmSeekBlob #define SetBlobClosable GmSetBlobClosable #define SetBlobTemporary GmSetBlobTemporary #define SetCacheView GmSetCacheView #define SetCacheViewPixels GmSetCacheViewPixels #define SetClientFilename GmSetClientFilename #define SetClientName GmSetClientName #define SetClientPath GmSetClientPath #define SetDelegateInfo GmSetDelegateInfo #define SetErrorHandler GmSetErrorHandler #define SetExceptionInfo GmSetExceptionInfo #define SetFatalErrorHandler GmSetFatalErrorHandler #define SetGeometry GmSetGeometry #define SetImage GmSetImage #define SetImageAttribute GmSetImageAttribute #define SetImageChannelDepth GmSetImageChannelDepth #define SetImageClipMask GmSetImageClipMask #define SetImageColor GmSetImageColor #define SetImageColorRegion GmSetImageColorRegion #define SetImageCompositeMask GmSetImageCompositeMask #define SetImageDepth GmSetImageDepth #define SetImageEx GmSetImageEx #define SetImageInfo GmSetImageInfo #define SetImageOpacity GmSetImageOpacity #define SetImagePixels GmSetImagePixels #define SetImagePixelsEx GmSetImagePixelsEx #define SetImageProfile GmSetImageProfile #define SetImageType GmSetImageType #define SetImageVirtualPixelMethod GmSetImageVirtualPixelMethod #define SetLogEventMask GmSetLogEventMask #define SetLogFormat GmSetLogFormat #define SetMagickInfo GmSetMagickInfo #define SetMagickRegistry GmSetMagickRegistry #define SetMagickResourceLimit GmSetMagickResourceLimit #define SetMonitorHandler GmSetMonitorHandler #define SetWarningHandler GmSetWarningHandler #define ShadeImage GmShadeImage #define SharpenImage GmSharpenImage #define SharpenImageChannel GmSharpenImageChannel #define ShaveImage GmShaveImage #define ShearImage GmShearImage #define SignatureImage GmSignatureImage #define SolarizeImage GmSolarizeImage #define SortColormapByIntensity GmSortColormapByIntensity #define SpliceImageIntoList GmSpliceImageIntoList #define SplitImageList GmSplitImageList #define SpreadImage GmSpreadImage #define StartTimer GmStartTimer #define SteganoImage GmSteganoImage #define StereoImage GmStereoImage #define StopTimer GmStopTimer #define StorageTypeToString GmStorageTypeToString #define StretchTypeToString GmStretchTypeToString #define StringToArgv GmStringToArgv #define StringToChannelType GmStringToChannelType #define StringToColorspaceType GmStringToColorspaceType #define StringToCompositeOperator GmStringToCompositeOperator #define StringToCompressionType GmStringToCompressionType #define StringToDouble GmStringToDouble #define StringToEndianType GmStringToEndianType #define StringToFilterTypes GmStringToFilterTypes #define StringToGravityType GmStringToGravityType #define StringToHighlightStyle GmStringToHighlightStyle #define StringToImageType GmStringToImageType #define StringToInterlaceType GmStringToInterlaceType #define StringToList GmStringToList #define StringToMetricType GmStringToMetricType #define StringToNoiseType GmStringToNoiseType #define StringToOrientationType GmStringToOrientationType #define StringToPreviewType GmStringToPreviewType #define StringToQuantumOperator GmStringToQuantumOperator #define StringToResolutionType GmStringToResolutionType #define StringToResourceType GmStringToResourceType #define StringToVirtualPixelMethod GmStringToVirtualPixelMethod #define Strip GmStrip #define StripImage GmStripImage #define StyleTypeToString GmStyleTypeToString #define SubstituteString GmSubstituteString #define SwirlImage GmSwirlImage #define SyncCacheView GmSyncCacheView #define SyncCacheViewPixels GmSyncCacheViewPixels #define SyncImage GmSyncImage #define SyncImagePixels GmSyncImagePixels #define SyncImagePixelsEx GmSyncImagePixelsEx #define SyncNextImageInList GmSyncNextImageInList #define SystemCommand GmSystemCommand #define TellBlob GmTellBlob #define TextureImage GmTextureImage #define ThresholdImage GmThresholdImage #define ThrowLoggedException GmThrowLoggedException #define ThumbnailImage GmThumbnailImage #define TimeImageCommand GmTimeImageCommand #define Tokenizer GmTokenizer #define TransformColorspace GmTransformColorspace #define TransformHSL GmTransformHSL #define TransformHWB GmTransformHWB #define TransformImage GmTransformImage #define TransformRGBImage GmTransformRGBImage #define TransformSignature GmTransformSignature #define TranslateText GmTranslateText #define TranslateTextEx GmTranslateTextEx #define TransparentImage GmTransparentImage #define UnlockSemaphoreInfo GmUnlockSemaphoreInfo #define UnmapBlob GmUnmapBlob #define UnregisterARTImage GmUnregisterARTImage #define UnregisterAVSImage GmUnregisterAVSImage #define UnregisterBMPImage GmUnregisterBMPImage #define UnregisterBRAILLEImage GmUnregisterBRAILLEImage #define UnregisterCALSImage GmUnregisterCALSImage #define UnregisterCAPTIONImage GmUnregisterCAPTIONImage #define UnregisterCINEONImage GmUnregisterCINEONImage #define UnregisterCMYKImage GmUnregisterCMYKImage #define UnregisterCUTImage GmUnregisterCUTImage #define UnregisterDCMImage GmUnregisterDCMImage #define UnregisterDCRAWImage GmUnregisterDCRAWImage #define UnregisterDIBImage GmUnregisterDIBImage #define UnregisterDPXImage GmUnregisterDPXImage #define UnregisterEPTImage GmUnregisterEPTImage #define UnregisterFAXImage GmUnregisterFAXImage #define UnregisterFITSImage GmUnregisterFITSImage #define UnregisterGIFImage GmUnregisterGIFImage #define UnregisterGRADIENTImage GmUnregisterGRADIENTImage #define UnregisterGRAYImage GmUnregisterGRAYImage #define UnregisterHISTOGRAMImage GmUnregisterHISTOGRAMImage #define UnregisterHRZImage GmUnregisterHRZImage #define UnregisterHTMLImage GmUnregisterHTMLImage #define UnregisterICONImage GmUnregisterICONImage #define UnregisterIDENTITYImage GmUnregisterIDENTITYImage #define UnregisterINFOImage GmUnregisterINFOImage #define UnregisterJNXImage GmUnregisterJNXImage #define UnregisterJP2Image GmUnregisterJP2Image #define UnregisterJPEGImage GmUnregisterJPEGImage #define UnregisterLABELImage GmUnregisterLABELImage #define UnregisterLOCALEImage GmUnregisterLOCALEImage #define UnregisterLOGOImage GmUnregisterLOGOImage #define UnregisterMACImage GmUnregisterMACImage #define UnregisterMAPImage GmUnregisterMAPImage #define UnregisterMATImage GmUnregisterMATImage #define UnregisterMATTEImage GmUnregisterMATTEImage #define UnregisterMETAImage GmUnregisterMETAImage #define UnregisterMIFFImage GmUnregisterMIFFImage #define UnregisterMONOImage GmUnregisterMONOImage #define UnregisterMPCImage GmUnregisterMPCImage #define UnregisterMPEGImage GmUnregisterMPEGImage #define UnregisterMPRImage GmUnregisterMPRImage #define UnregisterMSLImage GmUnregisterMSLImage #define UnregisterMTVImage GmUnregisterMTVImage #define UnregisterMVGImage GmUnregisterMVGImage #define UnregisterMagickInfo GmUnregisterMagickInfo #define UnregisterNULLImage GmUnregisterNULLImage #define UnregisterOTBImage GmUnregisterOTBImage #define UnregisterPALMImage GmUnregisterPALMImage #define UnregisterPCDImage GmUnregisterPCDImage #define UnregisterPCLImage GmUnregisterPCLImage #define UnregisterPCXImage GmUnregisterPCXImage #define UnregisterPDBImage GmUnregisterPDBImage #define UnregisterPDFImage GmUnregisterPDFImage #define UnregisterPICTImage GmUnregisterPICTImage #define UnregisterPIXImage GmUnregisterPIXImage #define UnregisterPLASMAImage GmUnregisterPLASMAImage #define UnregisterPNGImage GmUnregisterPNGImage #define UnregisterPNMImage GmUnregisterPNMImage #define UnregisterPREVIEWImage GmUnregisterPREVIEWImage #define UnregisterPS2Image GmUnregisterPS2Image #define UnregisterPS3Image GmUnregisterPS3Image #define UnregisterPSDImage GmUnregisterPSDImage #define UnregisterPSImage GmUnregisterPSImage #define UnregisterPWPImage GmUnregisterPWPImage #define UnregisterRGBImage GmUnregisterRGBImage #define UnregisterRLAImage GmUnregisterRLAImage #define UnregisterRLEImage GmUnregisterRLEImage #define UnregisterSCTImage GmUnregisterSCTImage #define UnregisterSFWImage GmUnregisterSFWImage #define UnregisterSGIImage GmUnregisterSGIImage #define UnregisterSTEGANOImage GmUnregisterSTEGANOImage #define UnregisterSUNImage GmUnregisterSUNImage #define UnregisterSVGImage GmUnregisterSVGImage #define UnregisterStaticModules GmUnregisterStaticModules #define UnregisterTGAImage GmUnregisterTGAImage #define UnregisterTIFFImage GmUnregisterTIFFImage #define UnregisterTILEImage GmUnregisterTILEImage #define UnregisterTIMImage GmUnregisterTIMImage #define UnregisterTOPOLImage GmUnregisterTOPOLImage #define UnregisterTTFImage GmUnregisterTTFImage #define UnregisterTXTImage GmUnregisterTXTImage #define UnregisterUILImage GmUnregisterUILImage #define UnregisterURLImage GmUnregisterURLImage #define UnregisterUYVYImage GmUnregisterUYVYImage #define UnregisterVICARImage GmUnregisterVICARImage #define UnregisterVIDImage GmUnregisterVIDImage #define UnregisterVIFFImage GmUnregisterVIFFImage #define UnregisterWBMPImage GmUnregisterWBMPImage #define UnregisterWEBPImage GmUnregisterWEBPImage #define UnregisterWMFImage GmUnregisterWMFImage #define UnregisterWPGImage GmUnregisterWPGImage #define UnregisterXBMImage GmUnregisterXBMImage #define UnregisterXCFImage GmUnregisterXCFImage #define UnregisterXCImage GmUnregisterXCImage #define UnregisterXImage GmUnregisterXImage #define UnregisterXPMImage GmUnregisterXPMImage #define UnregisterXWDImage GmUnregisterXWDImage #define UnregisterYUVImage GmUnregisterYUVImage #define UnsharpMaskImage GmUnsharpMaskImage #define UnsharpMaskImageChannel GmUnsharpMaskImageChannel #define UpdateSignature GmUpdateSignature #define WaveImage GmWaveImage #define WhiteThresholdImage GmWhiteThresholdImage #define WriteBlob GmWriteBlob #define WriteBlobByte GmWriteBlobByte #define WriteBlobFile GmWriteBlobFile #define WriteBlobLSBLong GmWriteBlobLSBLong #define WriteBlobLSBShort GmWriteBlobLSBShort #define WriteBlobLSBSignedLong GmWriteBlobLSBSignedLong #define WriteBlobLSBSignedShort GmWriteBlobLSBSignedShort #define WriteBlobMSBLong GmWriteBlobMSBLong #define WriteBlobMSBShort GmWriteBlobMSBShort #define WriteBlobMSBSignedLong GmWriteBlobMSBSignedLong #define WriteBlobMSBSignedShort GmWriteBlobMSBSignedShort #define WriteBlobString GmWriteBlobString #define WriteBlobStringEOL GmWriteBlobStringEOL #define WriteBlobStringWithEOL GmWriteBlobStringWithEOL #define WriteImage GmWriteImage #define WriteImages GmWriteImages #define WriteImagesFile GmWriteImagesFile #define ZoomImage GmZoomImage #endif /* defined(PREFIX_MAGICK_SYMBOLS) */ #endif /* defined(_MAGICK_SYMBOLS_H) */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/texture.h ================================================ /* Copyright (C) 2003 - 2009 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Texture Methods. */ #ifndef _MAGICK_TEXTURE_H #define _MAGICK_TEXTURE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Include declarations. */ #include "magick/image.h" #include "magick/error.h" extern MagickExport Image *ConstituteTextureImage(const unsigned long columns,const unsigned long rows, const Image *texture,ExceptionInfo *exception); extern MagickExport MagickPassFail TextureImage(Image *,const Image *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_TEXTURE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/timer.h ================================================ /* Copyright (C) 2003 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Timer Methods. */ #ifndef _MAGICK_TIMER_H #define _MAGICK_TIMER_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { UndefinedTimerState, StoppedTimerState, RunningTimerState } TimerState; /* Typedef declarations. */ typedef struct _Timer { double start, stop, total; } Timer; typedef struct _TimerInfo { Timer user, elapsed; TimerState state; unsigned long signature; } TimerInfo; /* Timer methods. */ extern MagickExport double GetElapsedTime(TimerInfo *), GetUserTime(TimerInfo *), GetTimerResolution(void); extern MagickExport unsigned int ContinueTimer(TimerInfo *); extern MagickExport void GetTimerInfo(TimerInfo *), ResetTimer(TimerInfo *), StartTimer(TimerInfo *time_info,const unsigned int reset), StopTimer(TimerInfo *time_info); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/transform.h ================================================ /* Copyright (C) 2003 - 2010 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. ImageMagick Image Transform Methods. */ #ifndef _MAGICK_TRANSFORM_H #define _MAGICK_TRANSFORM_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* defined(__cplusplus) || defined(c_plusplus) */ extern MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info,ExceptionInfo *exception), *CoalesceImages(const Image *image,ExceptionInfo *exception), *CropImage(const Image *image,const RectangleInfo *geometry,ExceptionInfo *exception), *DeconstructImages(const Image *image,ExceptionInfo *exception), *ExtentImage(const Image *image,const RectangleInfo *geometry,ExceptionInfo *exception), *FlattenImages(const Image *image,ExceptionInfo *exception), *FlipImage(const Image *image,ExceptionInfo *exception), *FlopImage(const Image *image,ExceptionInfo *exception), *MosaicImages(const Image *image,ExceptionInfo *exception), *RollImage(const Image *image,const long x_offset,const long y_offset,ExceptionInfo *exception), *ShaveImage(const Image *image,const RectangleInfo *shave_info,ExceptionInfo *exception); extern MagickExport MagickPassFail TransformImage(Image **,const char *,const char *); #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_TRANSFORM_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/type.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Drawing methods. */ #ifndef _MAGICK_TYPE_H #define _MAGICK_TYPE_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { NormalStretch, UltraCondensedStretch, ExtraCondensedStretch, CondensedStretch, SemiCondensedStretch, SemiExpandedStretch, ExpandedStretch, ExtraExpandedStretch, UltraExpandedStretch, AnyStretch } StretchType; typedef enum { NormalStyle, ItalicStyle, ObliqueStyle, AnyStyle } StyleType; /* Typedef declarations. */ typedef struct _TypeInfo { char *path, *name, *description, *family; StyleType style; StretchType stretch; unsigned long weight; char *encoding, *foundry, *format, *metrics, *glyphs; unsigned int stealth; unsigned long signature; struct _TypeInfo *previous, *next; } TypeInfo; /* Method declarations. */ extern MagickExport char **GetTypeList(const char *,unsigned long *); extern MagickExport MagickPassFail ListTypeInfo(FILE *,ExceptionInfo *); extern MagickExport const TypeInfo *GetTypeInfo(const char *,ExceptionInfo *), *GetTypeInfoByFamily(const char *,const StyleType,const StretchType, const unsigned long,ExceptionInfo *); #if defined(MAGICK_IMPLEMENTATION) # include "magick/type-private.h" #endif /* MAGICK_IMPLEMENTATION */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* _MAGICK_TYPE_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/utility.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Utility Methods. */ #ifndef _MAGICK_UTILITY_H #define _MAGICK_UTILITY_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Enum declarations. */ typedef enum { RootPath, HeadPath, TailPath, BasePath, ExtensionPath, MagickPath, SubImagePath, FullPath } PathType; /* Typedef declarations. */ typedef struct _TokenInfo { int state; unsigned int flag; long offset; char quote; } TokenInfo; /* Utilities methods. */ #undef ARG_NOT_USED #define ARG_NOT_USED(arg) (void) arg /* A callback function which behaves similar to strlcpy() except which optionally translates text while it is copied and always returns the number of characters which were actually copied rather than the number of characters which were available to copy. */ typedef size_t (*MagickTextTranslate)(char *dst, const char *src, const size_t size); extern MagickExport char *AcquireString(const char *), *AllocateString(const char *), *Base64Encode(const unsigned char *,const size_t,size_t *), *EscapeString(const char *,const char), *GetPageGeometry(const char *), **ListFiles(const char *,const char *,long *), **StringToArgv(const char *,int *), **StringToList(const char *), *TranslateText(const ImageInfo *,Image *,const char *), *TranslateTextEx(const ImageInfo *,Image *,const char *,MagickTextTranslate); extern MagickExport const char *GetClientFilename(void) MAGICK_FUNC_CONST, *GetClientName(void) MAGICK_FUNC_CONST, *GetClientPath(void) MAGICK_FUNC_CONST, *SetClientFilename(const char *), *SetClientName(const char *), *SetClientPath(const char *); extern MagickExport double StringToDouble(const char *,const double); extern MagickExport int GetGeometry(const char *,long *,long *,unsigned long *,unsigned long *), GlobExpression(const char *,const char *) MAGICK_FUNC_PURE, LocaleNCompare(const char *,const char *,const size_t) MAGICK_FUNC_PURE, LocaleCompare(const char *,const char *) MAGICK_FUNC_PURE, GetMagickDimension(const char *str,double *width,double *height,double *xoff,double *yoff), GetMagickGeometry(const char *geometry,long *x,long *y,unsigned long *width, unsigned long *height), MagickRandReentrant(unsigned int *seed) MAGICK_FUNC_DEPRECATED, MagickSpawnVP(const unsigned int verbose, const char *file, char *const argv[]), SystemCommand(const unsigned int,const char *), Tokenizer(TokenInfo *,unsigned,char *,size_t,char *,char *,char *,char *, char,char *,int *,char *); extern MagickExport unsigned int MagickRandNewSeed(void) MAGICK_FUNC_DEPRECATED; extern MagickExport unsigned char *Base64Decode(const char *, size_t *); extern MagickExport MagickPassFail CloneString(char **,const char *), ConcatenateString(char **,const char *), ExpandFilenames(int *,char ***), GetExecutionPath(char *), GetExecutionPathUsingName(char *), MagickCreateDirectoryPath(const char *dir,ExceptionInfo *exception); extern MagickExport MagickBool IsAccessible(const char *), IsAccessibleNoLogging(const char *), IsAccessibleAndNotEmpty(const char *), IsGeometry(const char *), IsGlob(const char *) MAGICK_FUNC_PURE, IsWriteable(const char *), MagickSceneFileName(char *filename,const char* filename_template, const char* scene_template,const MagickBool force,unsigned long scene), SubstituteString(char **buffer,const char *search,const char *replace); extern MagickExport unsigned long MultilineCensus(const char *) MAGICK_FUNC_PURE; extern MagickExport void AppendImageFormat(const char *,char *), DefineClientName(const char *), DefineClientPathAndName(const char *), ExpandFilename(char *), FormatSize(const magick_int64_t size,char *format), GetPathComponent(const char *,PathType,char *), GetToken(const char *,char **,char *) MAGICK_FUNC_DEPRECATED, LocaleLower(char *), LocaleUpper(char *), Strip(char *), SetGeometry(const Image *,RectangleInfo *); extern MagickExport void FormatString(char *string,const char *format,...) MAGICK_ATTRIBUTE((__format__ (__printf__,2,3))), FormatStringList(char *string,const char *format,va_list operands) MAGICK_ATTRIBUTE((__format__ (__printf__,2,0))), MagickFormatString(char *string,const size_t length,const char *format,...) MAGICK_ATTRIBUTE((__format__ (__printf__,3,4))), MagickFormatStringList(char *string,const size_t length,const char *format,va_list operands) MAGICK_ATTRIBUTE((__format__ (__printf__,3,0))); extern MagickExport magick_int64_t MagickSizeStrToInt64(const char *str,const unsigned int kilo); extern MagickExport size_t MagickGetToken(const char *start,char **end,char *token, const size_t buffer_length), MagickStripSpacesFromString(char *string), MagickStrlCat(char *dst, const char *src, const size_t size) MAGICK_FUNC_NONNULL, MagickStrlCpy(char *dst, const char *src, const size_t size) MAGICK_FUNC_NONNULL, MagickStrlCpyTrunc(char *dst, const char *src, const size_t size) MAGICK_FUNC_NONNULL; #if defined(MAGICK_IMPLEMENTATION) # include "magick/utility-private.h" #endif /* defined(MAGICK_IMPLEMENTATION) */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/magick/version.h ================================================ /* Copyright (C) 2003 - 2020 GraphicsMagick Group Copyright (C) 2002 ImageMagick Studio Copyright 1991-1999 E. I. du Pont de Nemours and Company This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick version and copyright. */ #ifndef _MAGICK_VERSION_H #define _MAGICK_VERSION_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* Define declarations. MagickLibVersion and MagickLibVersionNumber are defined differently than they are in ImageMagick. The three fields are based on library interface versioning. Each field in MagickLibVersion is one byte. The most significant field (third byte from the right) defines the library major interface, which is incremented whenever the library ABI changes incompatibly with preceding versions. The second field identifies an interface (a span) in a series of upward-compatible interfaces with the same major interface (such as when only new functions have) been added. The least significant field specifies the revision across 100% compatible interfaces. MagickLibVersionText provides a simple human-readable string for identifying the release. */ #define MagickPackageName "GraphicsMagick" #define MagickCopyright "Copyright (C) 2002-2020 GraphicsMagick Group.\nAdditional copyrights and licenses apply to this software.\nSee http://www.GraphicsMagick.org/www/Copyright.html for details." #define MagickLibVersion 0x242100 #define MagickLibVersionText "1.3.35" #define MagickLibVersionNumber 24,21,0 #define MagickChangeDate "20200223" #define MagickReleaseDate "2020-02-23" /* The MagickLibInterfaceNewest and MagickLibInterfaceOldest defines provide both the newest and oldest interfaces supported by the library. The 'newest' interface is incremented if new interfaces are added to the library. The 'oldest' interface is reset to the value of 'newest' if an existing interface is changed incompatibly, or an interface is removed. This scheme is similar to that used by ELF libraries. Note that the values used are related to those in MagickLibVersionNumber, but these are broken out and simplified so that they can be easily used in C pre-processor logic. */ #define MagickLibInterfaceNewest 24 #define MagickLibInterfaceOldest 3 #if (QuantumDepth == 8) #define MagickQuantumDepth "Q8" #elif (QuantumDepth == 16) #define MagickQuantumDepth "Q16" #elif (QuantumDepth == 32) #define MagickQuantumDepth "Q32" #else # error Unsupported quantum depth. #endif #define MagickVersion MagickPackageName " " MagickLibVersionText " " \ MagickReleaseDate " " MagickQuantumDepth " " MagickWebSite #define MagickWebSite "http://www." MagickPackageName ".org/" /* Method declarations. */ extern MagickExport const char *GetMagickCopyright(void) MAGICK_FUNC_CONST, *GetMagickVersion(unsigned long *) MAGICK_FUNC_CONST, *GetMagickWebSite(void) MAGICK_FUNC_CONST; #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/wand/drawing_wand.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group */ /* ImageMagick Drawing Wand API. */ #ifndef _MAGICK_DRAWING_WAND_H #define _MAGICK_DRAWING_WAND_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "wand/wand_symbols.h" #include "wand/pixel_wand.h" #undef CloneDrawingWand #define CloneDrawingWand MagickCloneDrawingWand #undef DestroyDrawingWand #define DestroyDrawingWand MagickDestroyDrawingWand #undef DrawAffine #define DrawAffine MagickDrawAffine #undef DrawAllocateWand #define DrawAllocateWand MagickDrawAllocateWand #undef DrawAnnotation #define DrawAnnotation MagickDrawAnnotation #undef DrawArc #define DrawArc MagickDrawArc #undef DrawBezier #define DrawBezier MagickDrawBezier #undef DrawClearException #define DrawClearException MagickDrawClearException #undef DrawCircle #define DrawCircle MagickDrawCircle #undef DrawColor #define DrawColor MagickDrawColor #undef DrawComment #define DrawComment MagickDrawComment #undef DrawComposite #define DrawComposite MagickDrawComposite #undef DrawEllipse #define DrawEllipse MagickDrawEllipse #undef DrawGetClipPath #define DrawGetClipPath MagickDrawGetClipPath #undef DrawGetClipRule #define DrawGetClipRule MagickDrawGetClipRule #undef DrawGetClipUnits #define DrawGetClipUnits MagickDrawGetClipUnits #undef DrawGetException #define DrawGetException MagickDrawGetException #undef DrawGetFillColor #define DrawGetFillColor MagickDrawGetFillColor #undef DrawGetFillOpacity #define DrawGetFillOpacity MagickDrawGetFillOpacity #undef DrawGetFillRule #define DrawGetFillRule MagickDrawGetFillRule #undef DrawGetFont #define DrawGetFont MagickDrawGetFont #undef DrawGetFontFamily #define DrawGetFontFamily MagickDrawGetFontFamily #undef DrawGetFontSize #define DrawGetFontSize MagickDrawGetFontSize #undef DrawGetFontStretch #define DrawGetFontStretch MagickDrawGetFontStretch #undef DrawGetFontStyle #define DrawGetFontStyle MagickDrawGetFontStyle #undef DrawGetFontWeight #define DrawGetFontWeight MagickDrawGetFontWeight #undef DrawGetGravity #define DrawGetGravity MagickDrawGetGravity #undef DrawGetStrokeAntialias #define DrawGetStrokeAntialias MagickDrawGetStrokeAntialias #undef DrawGetStrokeColor #define DrawGetStrokeColor MagickDrawGetStrokeColor #undef DrawGetStrokeDashArray #define DrawGetStrokeDashArray MagickDrawGetStrokeDashArray #undef DrawGetStrokeDashOffset #define DrawGetStrokeDashOffset MagickDrawGetStrokeDashOffset #undef DrawGetStrokeLineCap #define DrawGetStrokeLineCap MagickDrawGetStrokeLineCap #undef DrawGetStrokeLineJoin #define DrawGetStrokeLineJoin MagickDrawGetStrokeLineJoin #undef DrawGetStrokeMiterLimit #define DrawGetStrokeMiterLimit MagickDrawGetStrokeMiterLimit #undef DrawGetStrokeOpacity #define DrawGetStrokeOpacity MagickDrawGetStrokeOpacity #undef DrawGetStrokeWidth #define DrawGetStrokeWidth MagickDrawGetStrokeWidth #undef DrawGetTextAntialias #define DrawGetTextAntialias MagickDrawGetTextAntialias #undef DrawGetTextDecoration #define DrawGetTextDecoration MagickDrawGetTextDecoration #undef DrawGetTextEncoding #define DrawGetTextEncoding MagickDrawGetTextEncoding #undef DrawGetTextUnderColor #define DrawGetTextUnderColor MagickDrawGetTextUnderColor #undef DrawLine #define DrawLine MagickDrawLine #undef DrawMatte #define DrawMatte MagickDrawMatte #undef DrawPathClose #define DrawPathClose MagickDrawPathClose #undef DrawPathCurveToAbsolute #define DrawPathCurveToAbsolute MagickDrawPathCurveToAbsolute #undef DrawPathCurveToQuadraticBezierAbsolute #define DrawPathCurveToQuadraticBezierAbsolute MagickDrawPathCurveToQuadraticBezierAbsolute #undef DrawPathCurveToQuadraticBezierRelative #define DrawPathCurveToQuadraticBezierRelative MagickDrawPathCurveToQuadraticBezierRelative #undef DrawPathCurveToQuadraticBezierSmoothAbsolute #define DrawPathCurveToQuadraticBezierSmoothAbsolute MagickDrawPathCurveToQuadraticBezierSmoothAbsolute #undef DrawPathCurveToQuadraticBezierSmoothRelative #define DrawPathCurveToQuadraticBezierSmoothRelative MagickDrawPathCurveToQuadraticBezierSmoothRelative #undef DrawPathCurveToRelative #define DrawPathCurveToRelative MagickDrawPathCurveToRelative #undef DrawPathCurveToSmoothAbsolute #define DrawPathCurveToSmoothAbsolute MagickDrawPathCurveToSmoothAbsolute #undef DrawPathCurveToSmoothRelative #define DrawPathCurveToSmoothRelative MagickDrawPathCurveToSmoothRelative #undef DrawPathEllipticArcAbsolute #define DrawPathEllipticArcAbsolute MagickDrawPathEllipticArcAbsolute #undef DrawPathEllipticArcRelative #define DrawPathEllipticArcRelative MagickDrawPathEllipticArcRelative #undef DrawPathFinish #define DrawPathFinish MagickDrawPathFinish #undef DrawPathLineToAbsolute #define DrawPathLineToAbsolute MagickDrawPathLineToAbsolute #undef DrawPathLineToHorizontalAbsolute #define DrawPathLineToHorizontalAbsolute MagickDrawPathLineToHorizontalAbsolute #undef DrawPathLineToHorizontalRelative #define DrawPathLineToHorizontalRelative MagickDrawPathLineToHorizontalRelative #undef DrawPathLineToRelative #define DrawPathLineToRelative MagickDrawPathLineToRelative #undef DrawPathLineToVerticalAbsolute #define DrawPathLineToVerticalAbsolute MagickDrawPathLineToVerticalAbsolute #undef DrawPathLineToVerticalRelative #define DrawPathLineToVerticalRelative MagickDrawPathLineToVerticalRelative #undef DrawPathMoveToAbsolute #define DrawPathMoveToAbsolute MagickDrawPathMoveToAbsolute #undef DrawPathMoveToRelative #define DrawPathMoveToRelative MagickDrawPathMoveToRelative #undef DrawPathStart #define DrawPathStart MagickDrawPathStart #undef DrawPeekGraphicContext #define DrawPeekGraphicContext MagickDrawPeekGraphicContext #undef DrawPoint #define DrawPoint MagickDrawPoint #undef DrawPolygon #define DrawPolygon MagickDrawPolygon #undef DrawPolyline #define DrawPolyline MagickDrawPolyline #undef DrawPopClipPath #define DrawPopClipPath MagickDrawPopClipPath #undef DrawPopDefs #define DrawPopDefs MagickDrawPopDefs #undef DrawPopGraphicContext #define DrawPopGraphicContext MagickDrawPopGraphicContext #undef DrawPopPattern #define DrawPopPattern MagickDrawPopPattern #undef DrawPushClipPath #define DrawPushClipPath MagickDrawPushClipPath #undef DrawPushDefs #define DrawPushDefs MagickDrawPushDefs #undef DrawPushGraphicContext #define DrawPushGraphicContext MagickDrawPushGraphicContext #undef DrawPushPattern #define DrawPushPattern MagickDrawPushPattern #undef DrawRectangle #define DrawRectangle MagickDrawRectangle #undef DrawRender #define DrawRender MagickDrawRender #undef DrawRotate #define DrawRotate MagickDrawRotate #undef DrawRoundRectangle #define DrawRoundRectangle MagickDrawRoundRectangle #undef DrawScale #define DrawScale MagickDrawScale #undef DrawSetClipPath #define DrawSetClipPath MagickDrawSetClipPath #undef DrawSetClipRule #define DrawSetClipRule MagickDrawSetClipRule #undef DrawSetClipUnits #define DrawSetClipUnits MagickDrawSetClipUnits #undef DrawSetFillColor #define DrawSetFillColor MagickDrawSetFillColor #undef DrawSetFillOpacity #define DrawSetFillOpacity MagickDrawSetFillOpacity #undef DrawSetFillPatternURL #define DrawSetFillPatternURL MagickDrawSetFillPatternURL #undef DrawSetFillRule #define DrawSetFillRule MagickDrawSetFillRule #undef DrawSetFont #define DrawSetFont MagickDrawSetFont #undef DrawSetFontFamily #define DrawSetFontFamily MagickDrawSetFontFamily #undef DrawSetFontSize #define DrawSetFontSize MagickDrawSetFontSize #undef DrawSetFontStretch #define DrawSetFontStretch MagickDrawSetFontStretch #undef DrawSetFontStyle #define DrawSetFontStyle MagickDrawSetFontStyle #undef DrawSetFontWeight #define DrawSetFontWeight MagickDrawSetFontWeight #undef DrawSetGravity #define DrawSetGravity MagickDrawSetGravity #undef DrawSetStrokeAntialias #define DrawSetStrokeAntialias MagickDrawSetStrokeAntialias #undef DrawSetStrokeColor #define DrawSetStrokeColor MagickDrawSetStrokeColor #undef DrawSetStrokeDashArray #define DrawSetStrokeDashArray MagickDrawSetStrokeDashArray #undef DrawSetStrokeDashOffset #define DrawSetStrokeDashOffset MagickDrawSetStrokeDashOffset #undef DrawSetStrokeLineCap #define DrawSetStrokeLineCap MagickDrawSetStrokeLineCap #undef DrawSetStrokeLineJoin #define DrawSetStrokeLineJoin MagickDrawSetStrokeLineJoin #undef DrawSetStrokeMiterLimit #define DrawSetStrokeMiterLimit MagickDrawSetStrokeMiterLimit #undef DrawSetStrokeOpacity #define DrawSetStrokeOpacity MagickDrawSetStrokeOpacity #undef DrawSetStrokePatternURL #define DrawSetStrokePatternURL MagickDrawSetStrokePatternURL #undef DrawSetStrokeWidth #define DrawSetStrokeWidth MagickDrawSetStrokeWidth #undef DrawSetTextAntialias #define DrawSetTextAntialias MagickDrawSetTextAntialias #undef DrawSetTextDecoration #define DrawSetTextDecoration MagickDrawSetTextDecoration #undef DrawSetTextEncoding #define DrawSetTextEncoding MagickDrawSetTextEncoding #undef DrawSetTextUnderColor #define DrawSetTextUnderColor MagickDrawSetTextUnderColor #undef DrawSetViewbox #define DrawSetViewbox MagickDrawSetViewbox #undef DrawSkewX #define DrawSkewX MagickDrawSkewX #undef DrawSkewY #define DrawSkewY MagickDrawSkewY #undef DrawTranslate #define DrawTranslate MagickDrawTranslate #undef NewDrawingWand #define NewDrawingWand MagickNewDrawingWand typedef struct _DrawingWand DrawingWand; extern WandExport char *DrawGetClipPath(const DrawingWand *), *DrawGetException(const DrawingWand *,ExceptionType *), *DrawGetFont(const DrawingWand *), *DrawGetFontFamily(const DrawingWand *), *DrawGetTextEncoding(const DrawingWand *); extern WandExport ClipPathUnits DrawGetClipUnits(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport DecorationType DrawGetTextDecoration(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport double DrawGetFillOpacity(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetFontSize(const DrawingWand *) MAGICK_FUNC_PURE, *DrawGetStrokeDashArray(const DrawingWand *,unsigned long *), DrawGetStrokeDashOffset(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetStrokeOpacity(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetStrokeWidth(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport DrawInfo *DrawPeekGraphicContext(const DrawingWand *); extern WandExport DrawingWand *CloneDrawingWand(const DrawingWand *drawing_wand), *DrawAllocateWand(const DrawInfo *,Image *) MAGICK_ATTRIBUTE ((deprecated)), *NewDrawingWand(void); extern WandExport FillRule DrawGetClipRule(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetFillRule(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport GravityType DrawGetGravity(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport LineCap DrawGetStrokeLineCap(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport LineJoin DrawGetStrokeLineJoin(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport StretchType DrawGetFontStretch(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport StyleType DrawGetFontStyle(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport unsigned int DrawClearException(DrawingWand *), DrawGetStrokeAntialias(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetTextAntialias(const DrawingWand *) MAGICK_FUNC_PURE, DrawRender(const DrawingWand *) MAGICK_ATTRIBUTE ((deprecated)); /* Use MagickDrawImage() instead */ extern WandExport unsigned long DrawGetFontWeight(const DrawingWand *) MAGICK_FUNC_PURE, DrawGetStrokeMiterLimit(const DrawingWand *) MAGICK_FUNC_PURE; extern WandExport void DrawAffine(DrawingWand *,const AffineMatrix *), DrawAnnotation(DrawingWand *,const double,const double,const unsigned char *), DrawArc(DrawingWand *,const double,const double,const double,const double, const double,const double), DrawBezier(DrawingWand *,const unsigned long,const PointInfo *), DrawCircle(DrawingWand *,const double,const double,const double,const double), DrawColor(DrawingWand *,const double,const double,const PaintMethod), DrawComment(DrawingWand *,const char *), DestroyDrawingWand(DrawingWand *), DrawEllipse(DrawingWand *,const double,const double,const double,const double, const double,const double), DrawComposite(DrawingWand *,const CompositeOperator,const double,const double, const double,const double,const Image *), DrawGetFillColor(const DrawingWand *,PixelWand *), DrawGetStrokeColor(const DrawingWand *,PixelWand *), DrawGetTextUnderColor(const DrawingWand *,PixelWand *), DrawLine(DrawingWand *,const double, const double,const double,const double), DrawMatte(DrawingWand *,const double,const double,const PaintMethod), DrawPathClose(DrawingWand *), DrawPathCurveToAbsolute(DrawingWand *,const double,const double,const double, const double,const double,const double), DrawPathCurveToRelative(DrawingWand *,const double,const double,const double, const double,const double, const double), DrawPathCurveToQuadraticBezierAbsolute(DrawingWand *,const double, const double,const double,const double), DrawPathCurveToQuadraticBezierRelative(DrawingWand *,const double, const double,const double,const double), DrawPathCurveToQuadraticBezierSmoothAbsolute(DrawingWand *,const double, const double), DrawPathCurveToQuadraticBezierSmoothRelative(DrawingWand *,const double, const double), DrawPathCurveToSmoothAbsolute(DrawingWand *,const double,const double, const double,const double), DrawPathCurveToSmoothRelative(DrawingWand *,const double,const double, const double,const double), DrawPathEllipticArcAbsolute(DrawingWand *,const double,const double, const double,unsigned int,unsigned int,const double,const double), DrawPathEllipticArcRelative(DrawingWand *,const double,const double, const double,unsigned int,unsigned int,const double,const double), DrawPathFinish(DrawingWand *), DrawPathLineToAbsolute(DrawingWand *,const double,const double), DrawPathLineToRelative(DrawingWand *,const double,const double), DrawPathLineToHorizontalAbsolute(DrawingWand *,const double), DrawPathLineToHorizontalRelative(DrawingWand *,const double), DrawPathLineToVerticalAbsolute(DrawingWand *,const double), DrawPathLineToVerticalRelative(DrawingWand *,const double), DrawPathMoveToAbsolute(DrawingWand *,const double,const double), DrawPathMoveToRelative(DrawingWand *,const double,const double), DrawPathStart(DrawingWand *), DrawPoint(DrawingWand *,const double,const double), DrawPolygon(DrawingWand *,const unsigned long,const PointInfo *), DrawPolyline(DrawingWand *,const unsigned long,const PointInfo *), DrawPopClipPath(DrawingWand *), DrawPopDefs(DrawingWand *), DrawPopGraphicContext(DrawingWand *), DrawPopPattern(DrawingWand *), DrawPushClipPath(DrawingWand *,const char *), DrawPushDefs(DrawingWand *), DrawPushGraphicContext(DrawingWand *), DrawPushPattern(DrawingWand *,const char *,const double,const double, const double,const double), DrawRectangle(DrawingWand *,const double,const double,const double, const double), DrawRotate(DrawingWand *,const double), DrawRoundRectangle(DrawingWand *,double,double,double,double,double,double), DrawScale(DrawingWand *,const double,const double), DrawSetClipPath(DrawingWand *,const char *), DrawSetClipRule(DrawingWand *,const FillRule), DrawSetClipUnits(DrawingWand *,const ClipPathUnits), DrawSetFillColor(DrawingWand *,const PixelWand *), DrawSetFillOpacity(DrawingWand *,const double), DrawSetFillRule(DrawingWand *,const FillRule), DrawSetFillPatternURL(DrawingWand *,const char *), DrawSetFont(DrawingWand *,const char *), DrawSetFontFamily(DrawingWand *,const char *), DrawSetFontSize(DrawingWand *,const double), DrawSetFontStretch(DrawingWand *,const StretchType), DrawSetFontStyle(DrawingWand *,const StyleType), DrawSetFontWeight(DrawingWand *,const unsigned long), DrawSetGravity(DrawingWand *,const GravityType), DrawSkewX(DrawingWand *,const double), DrawSkewY(DrawingWand *,const double), DrawSetStrokeAntialias(DrawingWand *,const unsigned int), DrawSetStrokeColor(DrawingWand *,const PixelWand *), DrawSetStrokeDashArray(DrawingWand *,const unsigned long,const double *), DrawSetStrokeDashOffset(DrawingWand *,const double dashoffset), DrawSetStrokeLineCap(DrawingWand *,const LineCap), DrawSetStrokeLineJoin(DrawingWand *,const LineJoin), DrawSetStrokeMiterLimit(DrawingWand *,const unsigned long), DrawSetStrokeOpacity(DrawingWand *, const double), DrawSetStrokePatternURL(DrawingWand *,const char *), DrawSetStrokeWidth(DrawingWand *,const double), DrawSetTextAntialias(DrawingWand *,const unsigned int), DrawSetTextDecoration(DrawingWand *,const DecorationType), DrawSetTextEncoding(DrawingWand *,const char *), DrawSetTextUnderColor(DrawingWand *,const PixelWand *), DrawSetViewbox(DrawingWand *,unsigned long,unsigned long,unsigned long, unsigned long), DrawTranslate(DrawingWand *,const double,const double); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/wand/magick_wand.h ================================================ /* Copyright (C) 2003-2019 GraphicsMagick Group */ /* ImageMagick MagickWand interface. */ #ifndef _MAGICK_WAND_H #define _MAGICK_WAND_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if defined(_VISUALC_) # if defined(_MT) && defined(_DLL) && !defined(_LIB) # pragma warning( disable: 4273 ) # if !defined(_WANDLIB_) # define WandExport __declspec(dllimport) # else # define WandExport __declspec(dllexport) # endif # else # define WandExport # endif # pragma warning(disable : 4018) # pragma warning(disable : 4244) # pragma warning(disable : 4142) #else # define WandExport #endif #include "magick/api.h" #include "wand/wand_symbols.h" #include "wand/drawing_wand.h" #include "wand/pixel_wand.h" /* ImageMagick compatibility definitions */ #define MagickSizeType magick_int64_t #define ReplaceCompositeOp CopyCompositeOp #define IndexChannel BlackChannel #define AreaResource UndefinedResource /* not supported */ extern WandExport int FormatMagickString(char *,const size_t,const char *,...) MAGICK_ATTRIBUTE((format (printf,3,4))); extern WandExport size_t CopyMagickString(char *,const char *,const size_t); typedef struct _MagickWand MagickWand; extern WandExport char *MagickDescribeImage(MagickWand *), *MagickGetConfigureInfo(MagickWand *,const char *) MAGICK_FUNC_CONST, *MagickGetException(const MagickWand *,ExceptionType *), *MagickGetFilename(const MagickWand *), *MagickGetImageAttribute(MagickWand *, const char *), *MagickGetImageFilename(MagickWand *), *MagickGetImageFormat(MagickWand *), *MagickGetImageSignature(MagickWand *), **MagickQueryFonts(const char *,unsigned long *), **MagickQueryFormats(const char *,unsigned long *); extern WandExport CompositeOperator MagickGetImageCompose(MagickWand *); extern WandExport ColorspaceType MagickGetImageColorspace(MagickWand *); extern WandExport CompressionType MagickGetImageCompression(MagickWand *); extern WandExport const char *MagickGetCopyright(void) MAGICK_FUNC_CONST, *MagickGetHomeURL(void) MAGICK_FUNC_CONST, *MagickGetImageGeometry(MagickWand *), *MagickGetPackageName(void) MAGICK_FUNC_CONST, *MagickGetQuantumDepth(unsigned long *), *MagickGetReleaseDate(void) MAGICK_FUNC_CONST, *MagickGetVersion(unsigned long *) MAGICK_FUNC_CONST; extern WandExport DisposeType MagickGetImageDispose(MagickWand *); extern WandExport double MagickGetImageGamma(MagickWand *), MagickGetImageFuzz(MagickWand *), *MagickGetSamplingFactors(MagickWand *,unsigned long *), *MagickQueryFontMetrics(MagickWand *,const DrawingWand *,const char *); extern WandExport GravityType MagickGetImageGravity(MagickWand *wand); extern WandExport ImageType MagickGetImageType(MagickWand *); extern WandExport ImageType MagickGetImageSavedType(MagickWand *) MAGICK_FUNC_CONST; extern WandExport InterlaceType MagickGetImageInterlaceScheme(MagickWand *); extern WandExport long MagickGetImageIndex(MagickWand *); extern WandExport MagickSizeType MagickGetImageSize(MagickWand *); extern WandExport MagickWand *CloneMagickWand(const MagickWand *), *MagickAppendImages(MagickWand *,const unsigned int), *MagickAverageImages(MagickWand *), *MagickCoalesceImages(MagickWand *), *MagickCompareImageChannels(MagickWand *,const MagickWand *,const ChannelType, const MetricType,double *), *MagickCompareImages(MagickWand *,const MagickWand *,const MetricType, double *), *MagickDeconstructImages(MagickWand *), *MagickFlattenImages(MagickWand *), *MagickFxImage(MagickWand *,const char *), *MagickFxImageChannel(MagickWand *,const ChannelType,const char *), *MagickGetImage(MagickWand *), *MagickMorphImages(MagickWand *,const unsigned long), *MagickMosaicImages(MagickWand *), *MagickMontageImage(MagickWand *,const DrawingWand *,const char *, const char *,const MontageMode,const char *), *MagickPreviewImages(MagickWand *wand,const PreviewType), *MagickSteganoImage(MagickWand *,const MagickWand *,const long), *MagickStereoImage(MagickWand *,const MagickWand *), *MagickTextureImage(MagickWand *,const MagickWand *), *MagickTransformImage(MagickWand *,const char *,const char *), *NewMagickWand(void); extern WandExport OrientationType MagickGetImageOrientation(MagickWand *); extern WandExport PixelWand **MagickGetImageHistogram(MagickWand *,unsigned long *); extern WandExport RenderingIntent MagickGetImageRenderingIntent(MagickWand *); extern WandExport ResolutionType MagickGetImageUnits(MagickWand *); extern WandExport unsigned int DestroyMagickWand(MagickWand *), MagickAdaptiveThresholdImage(MagickWand *,const unsigned long, const unsigned long,const long), MagickAddImage(MagickWand *,const MagickWand *), MagickAddNoiseImage(MagickWand *,const NoiseType), MagickAffineTransformImage(MagickWand *,const DrawingWand *), MagickAnnotateImage(MagickWand *,const DrawingWand *,const double, const double,const double,const char *), MagickAnimateImages(MagickWand *,const char *), MagickAutoOrientImage(MagickWand *wand,const OrientationType), MagickBlackThresholdImage(MagickWand *,const PixelWand *), MagickBlurImage(MagickWand *,const double,const double), MagickBorderImage(MagickWand *,const PixelWand *,const unsigned long, const unsigned long), MagickCdlImage(MagickWand *wand,const char *cdl), MagickCharcoalImage(MagickWand *,const double,const double), MagickChopImage(MagickWand *,const unsigned long,const unsigned long, const long,const long), MagickClipImage(MagickWand *), MagickClipPathImage(MagickWand *,const char *,const unsigned int), MagickColorFloodfillImage(MagickWand *,const PixelWand *,const double, const PixelWand *,const long,const long), MagickColorizeImage(MagickWand *,const PixelWand *,const PixelWand *), MagickCommentImage(MagickWand *,const char *), MagickCompositeImage(MagickWand *,const MagickWand *,const CompositeOperator, const long,const long), MagickContrastImage(MagickWand *,const unsigned int), MagickConvolveImage(MagickWand *,const unsigned long,const double *), MagickCropImage(MagickWand *,const unsigned long,const unsigned long, const long,const long), MagickCycleColormapImage(MagickWand *,const long), MagickDespeckleImage(MagickWand *), MagickDisplayImage(MagickWand *,const char *), MagickDisplayImages(MagickWand *,const char *), MagickDrawImage(MagickWand *,const DrawingWand *), MagickEdgeImage(MagickWand *,const double), MagickEmbossImage(MagickWand *,const double,const double), MagickEnhanceImage(MagickWand *), MagickEqualizeImage(MagickWand *), MagickExtentImage(MagickWand *,const size_t,const size_t,const ssize_t, const ssize_t), MagickFlipImage(MagickWand *), MagickFlopImage(MagickWand *), MagickFrameImage(MagickWand *,const PixelWand *,const unsigned long, const unsigned long,const long,const long), MagickGammaImage(MagickWand *,const double), MagickGammaImageChannel(MagickWand *,const ChannelType,const double), MagickGetImageBackgroundColor(MagickWand *,PixelWand *), MagickGetImageBluePrimary(MagickWand *,double *,double *), MagickGetImageBorderColor(MagickWand *,PixelWand *), MagickGetImageBoundingBox(MagickWand *wand,const double fuzz, unsigned long *width,unsigned long *height,long *x, long *y), MagickGetImageChannelExtrema(MagickWand *,const ChannelType,unsigned long *, unsigned long *), MagickGetImageChannelMean(MagickWand *,const ChannelType,double *,double *), MagickGetImageColormapColor(MagickWand *,const unsigned long,PixelWand *), MagickGetImageExtrema(MagickWand *,unsigned long *,unsigned long *), MagickGetImageGreenPrimary(MagickWand *,double *,double *), MagickGetImageMatte(MagickWand *), MagickGetImageMatteColor(MagickWand *,PixelWand *), MagickGetImagePage(MagickWand *wand, unsigned long *width,unsigned long *height,long *x,long *y), MagickGetImagePixels(MagickWand *,const long,const long,const unsigned long, const unsigned long,const char *,const StorageType,unsigned char *), MagickGetImageRedPrimary(MagickWand *,double *,double *), MagickGetImageResolution(MagickWand *,double *,double *), MagickGetImageWhitePoint(MagickWand *,double *,double *), MagickGetSize(const MagickWand *,unsigned long *,unsigned long *), MagickHaldClutImage(MagickWand *wand,const MagickWand *clut_wand), MagickHasColormap(MagickWand *,unsigned int *), MagickHasNextImage(MagickWand *), MagickHasPreviousImage(MagickWand *), MagickImplodeImage(MagickWand *,const double), MagickIsGrayImage(MagickWand *,unsigned int *), MagickIsMonochromeImage(MagickWand *,unsigned int *), MagickIsOpaqueImage(MagickWand *,unsigned int *), MagickIsPaletteImage(MagickWand *,unsigned int *), MagickLabelImage(MagickWand *,const char *), MagickLevelImage(MagickWand *,const double,const double,const double), MagickLevelImageChannel(MagickWand *,const ChannelType,const double, const double,const double), MagickMagnifyImage(MagickWand *), MagickMapImage(MagickWand *,const MagickWand *,const unsigned int), MagickMatteFloodfillImage(MagickWand *,const Quantum,const double, const PixelWand *,const long,const long), MagickMedianFilterImage(MagickWand *,const double), MagickMinifyImage(MagickWand *), MagickModulateImage(MagickWand *,const double,const double,const double), MagickMotionBlurImage(MagickWand *,const double,const double,const double), MagickNegateImage(MagickWand *,const unsigned int), MagickNegateImageChannel(MagickWand *,const ChannelType,const unsigned int), MagickNextImage(MagickWand *), MagickNormalizeImage(MagickWand *), MagickOilPaintImage(MagickWand *,const double), MagickOpaqueImage(MagickWand *,const PixelWand *,const PixelWand *, const double), MagickOperatorImageChannel(MagickWand *,const ChannelType,const QuantumOperator, const double), MagickPingImage(MagickWand *,const char *), MagickPreviousImage(MagickWand *), MagickProfileImage(MagickWand *,const char *,const unsigned char *, const unsigned long), MagickQuantizeImage(MagickWand *,const unsigned long,const ColorspaceType, const unsigned long,const unsigned int,const unsigned int), MagickQuantizeImages(MagickWand *,const unsigned long,const ColorspaceType, const unsigned long,const unsigned int,const unsigned int), MagickRadialBlurImage(MagickWand *,const double), MagickRaiseImage(MagickWand *,const unsigned long,const unsigned long, const long,const long,const unsigned int), MagickReadImage(MagickWand *,const char *), MagickReadImageBlob(MagickWand *,const unsigned char *,const size_t length), MagickReadImageFile(MagickWand *,FILE *), MagickReduceNoiseImage(MagickWand *,const double), MagickRelinquishMemory(void *), MagickRemoveImage(MagickWand *), MagickRemoveImageOption(MagickWand *wand,const char *,const char *), MagickResampleImage(MagickWand *,const double,const double,const FilterTypes, const double), MagickResizeImage(MagickWand *,const unsigned long,const unsigned long, const FilterTypes,const double), MagickRollImage(MagickWand *,const long,const long), MagickRotateImage(MagickWand *,const PixelWand *,const double), MagickSampleImage(MagickWand *,const unsigned long,const unsigned long), MagickScaleImage(MagickWand *,const unsigned long,const unsigned long), MagickSeparateImageChannel(MagickWand *,const ChannelType), MagickSetCompressionQuality(MagickWand *wand,const unsigned long quality), MagickSetFilename(MagickWand *,const char *), MagickSetFormat(MagickWand *,const char *), MagickSetImage(MagickWand *,const MagickWand *), MagickSetImageAttribute(MagickWand *,const char *, const char *), MagickSetImageBackgroundColor(MagickWand *,const PixelWand *), MagickSetImageBluePrimary(MagickWand *,const double,const double), MagickSetImageBorderColor(MagickWand *,const PixelWand *), MagickSetImageChannelDepth(MagickWand *,const ChannelType, const unsigned long), MagickSetImageColormapColor(MagickWand *,const unsigned long, const PixelWand *), MagickSetImageCompose(MagickWand *,const CompositeOperator), MagickSetImageCompression(MagickWand *,const CompressionType), MagickSetImageDelay(MagickWand *,const unsigned long), MagickSetImageDepth(MagickWand *,const unsigned long), MagickSetImageDispose(MagickWand *,const DisposeType), MagickSetImageColorspace(MagickWand *,const ColorspaceType), MagickSetImageGreenPrimary(MagickWand *,const double,const double), MagickSetImageGamma(MagickWand *,const double), MagickSetImageGeometry(MagickWand *,const char *), MagickSetImageGravity(MagickWand *,const GravityType), MagickSetImageFilename(MagickWand *,const char *), MagickSetImageFormat(MagickWand *wand,const char *format), MagickSetImageFuzz(MagickWand *,const double), MagickSetImageIndex(MagickWand *,const long), MagickSetImageInterlaceScheme(MagickWand *,const InterlaceType), MagickSetImageIterations(MagickWand *,const unsigned long), MagickSetImageMatte(MagickWand *,const unsigned int), MagickSetImageMatteColor(MagickWand *,const PixelWand *), MagickSetImageOption(MagickWand *,const char *,const char *,const char *), MagickSetImageOrientation(MagickWand *,const OrientationType), MagickSetImagePage(MagickWand *wand, const unsigned long width,const unsigned long height,const long x, const long y), MagickSetImagePixels(MagickWand *,const long,const long,const unsigned long, const unsigned long,const char *,const StorageType,unsigned char *), MagickSetImageRedPrimary(MagickWand *,const double,const double), MagickSetImageRenderingIntent(MagickWand *,const RenderingIntent), MagickSetImageResolution(MagickWand *,const double,const double), MagickSetImageScene(MagickWand *,const unsigned long), MagickSetImageType(MagickWand *,const ImageType), MagickSetImageSavedType(MagickWand *,const ImageType), MagickSetImageUnits(MagickWand *,const ResolutionType), MagickSetImageVirtualPixelMethod(MagickWand *,const VirtualPixelMethod), MagickSetPassphrase(MagickWand *,const char *), MagickSetImageProfile(MagickWand *,const char *,const unsigned char *, const unsigned long), MagickSetResolution(MagickWand *wand, const double x_resolution,const double y_resolution), MagickSetResolutionUnits(MagickWand *wand,const ResolutionType units), MagickSetResourceLimit(const ResourceType type,const unsigned long limit), MagickSetSamplingFactors(MagickWand *,const unsigned long,const double *), MagickSetSize(MagickWand *,const unsigned long,const unsigned long), MagickSetImageWhitePoint(MagickWand *,const double,const double), MagickSetInterlaceScheme(MagickWand *,const InterlaceType), MagickSharpenImage(MagickWand *,const double,const double), MagickShaveImage(MagickWand *,const unsigned long,const unsigned long), MagickShearImage(MagickWand *,const PixelWand *,const double,const double), MagickSolarizeImage(MagickWand *,const double), MagickSpreadImage(MagickWand *,const double), MagickStripImage(MagickWand *), MagickSwirlImage(MagickWand *,const double), MagickTintImage(MagickWand *,const PixelWand *,const PixelWand *), MagickThresholdImage(MagickWand *,const double), MagickThresholdImageChannel(MagickWand *,const ChannelType,const double), MagickTransparentImage(MagickWand *,const PixelWand *,const Quantum, const double), MagickTrimImage(MagickWand *,const double), MagickUnsharpMaskImage(MagickWand *,const double,const double,const double, const double), MagickWaveImage(MagickWand *,const double,const double), MagickWhiteThresholdImage(MagickWand *,const PixelWand *), MagickWriteImage(MagickWand *,const char *), MagickWriteImageFile(MagickWand *,FILE *), MagickWriteImagesFile(MagickWand *,FILE *,const unsigned int), MagickWriteImages(MagickWand *,const char *,const unsigned int); extern WandExport unsigned long MagickGetImageColors(MagickWand *), MagickGetImageDelay(MagickWand *), MagickGetImageChannelDepth(MagickWand *,const ChannelType), MagickGetImageDepth(MagickWand *), MagickGetImageHeight(MagickWand *), MagickGetImageIterations(MagickWand *), MagickGetImageScene(MagickWand *), MagickGetImageWidth(MagickWand *), MagickGetNumberImages(MagickWand *), MagickGetResourceLimit(const ResourceType); extern WandExport VirtualPixelMethod MagickGetImageVirtualPixelMethod(MagickWand *); extern WandExport unsigned char *MagickGetImageProfile(MagickWand *,const char *,unsigned long *), *MagickRemoveImageProfile(MagickWand *,const char *,unsigned long *), *MagickWriteImageBlob(MagickWand *,size_t *); extern WandExport void MagickClearException(MagickWand *), MagickResetIterator(MagickWand *); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/wand/pixel_wand.h ================================================ /* Copyright (C) 2003-2009 GraphicsMagick Group Copyright (C) 2003 ImageMagick Studio This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. GraphicsMagick Pixel Wand Methods. */ #ifndef _MAGICK_PIXEL_WAND_H #define _MAGICK_PIXEL_WAND_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include "wand/wand_symbols.h" typedef struct _PixelWand PixelWand; extern WandExport char *PixelGetColorAsString(const PixelWand *); extern WandExport double PixelGetBlack(const PixelWand *) MAGICK_FUNC_PURE, PixelGetBlue(const PixelWand *) MAGICK_FUNC_PURE, PixelGetCyan(const PixelWand *) MAGICK_FUNC_PURE, PixelGetGreen(const PixelWand *) MAGICK_FUNC_PURE, PixelGetMagenta(const PixelWand *) MAGICK_FUNC_PURE, PixelGetOpacity(const PixelWand *) MAGICK_FUNC_PURE, PixelGetRed(const PixelWand *) MAGICK_FUNC_PURE, PixelGetYellow(const PixelWand *) MAGICK_FUNC_PURE; extern WandExport PixelWand *ClonePixelWand(const PixelWand *), **ClonePixelWands(const PixelWand **,const unsigned long), *NewPixelWand(void), **NewPixelWands(const unsigned long); extern WandExport Quantum PixelGetBlackQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetBlueQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetCyanQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetGreenQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetMagentaQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetOpacityQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetRedQuantum(const PixelWand *) MAGICK_FUNC_PURE, PixelGetYellowQuantum(const PixelWand *) MAGICK_FUNC_PURE; extern WandExport unsigned int PixelSetColor(PixelWand *,const char *); extern WandExport unsigned long PixelGetColorCount(const PixelWand *) MAGICK_FUNC_PURE; extern WandExport void DestroyPixelWand(PixelWand *), PixelGetQuantumColor(const PixelWand *,PixelPacket *), PixelSetBlack(PixelWand *,const double), PixelSetBlackQuantum(PixelWand *,const Quantum), PixelSetBlue(PixelWand *,const double), PixelSetBlueQuantum(PixelWand *,const Quantum), PixelSetColorCount(PixelWand *,const unsigned long), PixelSetCyan(PixelWand *,const double), PixelSetCyanQuantum(PixelWand *,const Quantum), PixelSetGreen(PixelWand *,const double), PixelSetGreenQuantum(PixelWand *,const Quantum), PixelSetMagenta(PixelWand *,const double), PixelSetMagentaQuantum(PixelWand *,const Quantum), PixelSetOpacity(PixelWand *,const double), PixelSetOpacityQuantum(PixelWand *,const Quantum), PixelSetQuantumColor(PixelWand *,PixelPacket *), PixelSetRed(PixelWand *,const double), PixelSetRedQuantum(PixelWand *,const Quantum), PixelSetYellow(PixelWand *,const double), PixelSetYellowQuantum(PixelWand *,const Quantum); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/wand/wand_api.h ================================================ /* Copyright (C) 2003-2018 GraphicsMagick Group GraphicsMagick Wand API Methods */ #ifndef _MAGICK_WAND_API_H #define _MAGICK_WAND_API_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include #include #if defined(_VISUALC_) /** * Under VISUALC we have single threaded static libraries, or * mutli-threaded DLLs using the multithreaded runtime DLLs. **/ # if defined(_MT) && defined(_DLL) && !defined(_LIB) # pragma warning( disable: 4273 ) /* Disable the stupid dll linkage warnings */ # if !defined(_WANDLIB_) # define WandExport __declspec(dllimport) # else # define WandExport __declspec(dllexport) # endif # else # define WandExport # endif # pragma warning(disable : 4018) # pragma warning(disable : 4244) # pragma warning(disable : 4142) #else # define WandExport #endif #include #include #include #if defined(__cplusplus) || defined(c_plusplus) } #endif /* defined(__cplusplus) || defined(c_plusplus) */ #endif /* _MAGICK_WAND_API_H */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/include/wand/wand_symbols.h ================================================ /* Copyright (C) 2012-2018 GraphicsMagick Group This program is covered by multiple licenses, which are described in Copyright.txt. You should have received a copy of Copyright.txt with this package; otherwise see http://www.graphicsmagick.org/www/Copyright.html. Library symbol name-scoping support. */ #if !defined(_MAGICK_WAND_SYMBOLS_H) #define _MAGICK_WAND_SYMBOLS_H #if defined(PREFIX_MAGICK_SYMBOLS) #define CloneMagickWand GmCloneMagickWand #define ClonePixelWand GmClonePixelWand #define ClonePixelWands GmClonePixelWands #define CopyMagickString GmCopyMagickString #define DestroyMagickWand GmDestroyMagickWand #define DestroyPixelWand GmDestroyPixelWand #define FormatMagickString GmFormatMagickString #define FormatMagickStringList GmFormatMagickStringList #define MagickAdaptiveThresholdImage GmMagickAdaptiveThresholdImage #define MagickAddImage GmMagickAddImage #define MagickAddNoiseImage GmMagickAddNoiseImage #define MagickAffineTransformImage GmMagickAffineTransformImage #define MagickAnimateImages GmMagickAnimateImages #define MagickAnnotateImage GmMagickAnnotateImage #define MagickAppendImages GmMagickAppendImages #define MagickAutoOrientImage GmMagickAutoOrientImage #define MagickAverageImages GmMagickAverageImages #define MagickBlackThresholdImage GmMagickBlackThresholdImage #define MagickBlurImage GmMagickBlurImage #define MagickBorderImage GmMagickBorderImage #define MagickCdlImage GmMagickCdlImage #define MagickCharcoalImage GmMagickCharcoalImage #define MagickChopImage GmMagickChopImage #define MagickClearException GmMagickClearException #define MagickClipImage GmMagickClipImage #define MagickClipPathImage GmMagickClipPathImage #define MagickCloneDrawingWand GmMagickCloneDrawingWand #define MagickCoalesceImages GmMagickCoalesceImages #define MagickColorFloodfillImage GmMagickColorFloodfillImage #define MagickColorizeImage GmMagickColorizeImage #define MagickCommentImage GmMagickCommentImage #define MagickCompareImageChannels GmMagickCompareImageChannels #define MagickCompareImages GmMagickCompareImages #define MagickCompositeImage GmMagickCompositeImage #define MagickContrastImage GmMagickContrastImage #define MagickConvolveImage GmMagickConvolveImage #define MagickCropImage GmMagickCropImage #define MagickCycleColormapImage GmMagickCycleColormapImage #define MagickDeconstructImages GmMagickDeconstructImages #define MagickDescribeImage GmMagickDescribeImage #define MagickDespeckleImage GmMagickDespeckleImage #define MagickDestroyDrawingWand GmMagickDestroyDrawingWand #define MagickDisplayImage GmMagickDisplayImage #define MagickDisplayImages GmMagickDisplayImages #define MagickDrawAffine GmMagickDrawAffine #define MagickDrawAllocateWand GmMagickDrawAllocateWand #define MagickDrawAnnotation GmMagickDrawAnnotation #define MagickDrawArc GmMagickDrawArc #define MagickDrawBezier GmMagickDrawBezier #define MagickDrawCircle GmMagickDrawCircle #define MagickDrawClearException GmMagickDrawClearException #define MagickDrawColor GmMagickDrawColor #define MagickDrawComment GmMagickDrawComment #define MagickDrawComposite GmMagickDrawComposite #define MagickDrawEllipse GmMagickDrawEllipse #define MagickDrawGetClipPath GmMagickDrawGetClipPath #define MagickDrawGetClipRule GmMagickDrawGetClipRule #define MagickDrawGetClipUnits GmMagickDrawGetClipUnits #define MagickDrawGetException GmMagickDrawGetException #define MagickDrawGetFillColor GmMagickDrawGetFillColor #define MagickDrawGetFillOpacity GmMagickDrawGetFillOpacity #define MagickDrawGetFillRule GmMagickDrawGetFillRule #define MagickDrawGetFont GmMagickDrawGetFont #define MagickDrawGetFontFamily GmMagickDrawGetFontFamily #define MagickDrawGetFontSize GmMagickDrawGetFontSize #define MagickDrawGetFontStretch GmMagickDrawGetFontStretch #define MagickDrawGetFontStyle GmMagickDrawGetFontStyle #define MagickDrawGetFontWeight GmMagickDrawGetFontWeight #define MagickDrawGetGravity GmMagickDrawGetGravity #define MagickDrawGetStrokeAntialias GmMagickDrawGetStrokeAntialias #define MagickDrawGetStrokeColor GmMagickDrawGetStrokeColor #define MagickDrawGetStrokeDashArray GmMagickDrawGetStrokeDashArray #define MagickDrawGetStrokeDashOffset GmMagickDrawGetStrokeDashOffset #define MagickDrawGetStrokeLineCap GmMagickDrawGetStrokeLineCap #define MagickDrawGetStrokeLineJoin GmMagickDrawGetStrokeLineJoin #define MagickDrawGetStrokeMiterLimit GmMagickDrawGetStrokeMiterLimit #define MagickDrawGetStrokeOpacity GmMagickDrawGetStrokeOpacity #define MagickDrawGetStrokeWidth GmMagickDrawGetStrokeWidth #define MagickDrawGetTextAntialias GmMagickDrawGetTextAntialias #define MagickDrawGetTextDecoration GmMagickDrawGetTextDecoration #define MagickDrawGetTextEncoding GmMagickDrawGetTextEncoding #define MagickDrawGetTextUnderColor GmMagickDrawGetTextUnderColor #define MagickDrawImage GmMagickDrawImage #define MagickDrawLine GmMagickDrawLine #define MagickDrawMatte GmMagickDrawMatte #define MagickDrawPathClose GmMagickDrawPathClose #define MagickDrawPathCurveToAbsolute GmMagickDrawPathCurveToAbsolute #define MagickDrawPathCurveToQuadraticBezierAbsolute GmMagickDrawPathCurveToQuadraticBezierAbsolute #define MagickDrawPathCurveToQuadraticBezierRelative GmMagickDrawPathCurveToQuadraticBezierRelative #define MagickDrawPathCurveToQuadraticBezierSmoothAbsolute GmMagickDrawPathCurveToQuadraticBezierSmoothAbsolute #define MagickDrawPathCurveToQuadraticBezierSmoothRelative GmMagickDrawPathCurveToQuadraticBezierSmoothRelative #define MagickDrawPathCurveToRelative GmMagickDrawPathCurveToRelative #define MagickDrawPathCurveToSmoothAbsolute GmMagickDrawPathCurveToSmoothAbsolute #define MagickDrawPathCurveToSmoothRelative GmMagickDrawPathCurveToSmoothRelative #define MagickDrawPathEllipticArcAbsolute GmMagickDrawPathEllipticArcAbsolute #define MagickDrawPathEllipticArcRelative GmMagickDrawPathEllipticArcRelative #define MagickDrawPathFinish GmMagickDrawPathFinish #define MagickDrawPathLineToAbsolute GmMagickDrawPathLineToAbsolute #define MagickDrawPathLineToHorizontalAbsolute GmMagickDrawPathLineToHorizontalAbsolute #define MagickDrawPathLineToHorizontalRelative GmMagickDrawPathLineToHorizontalRelative #define MagickDrawPathLineToRelative GmMagickDrawPathLineToRelative #define MagickDrawPathLineToVerticalAbsolute GmMagickDrawPathLineToVerticalAbsolute #define MagickDrawPathLineToVerticalRelative GmMagickDrawPathLineToVerticalRelative #define MagickDrawPathMoveToAbsolute GmMagickDrawPathMoveToAbsolute #define MagickDrawPathMoveToRelative GmMagickDrawPathMoveToRelative #define MagickDrawPathStart GmMagickDrawPathStart #define MagickDrawPeekGraphicContext GmMagickDrawPeekGraphicContext #define MagickDrawPoint GmMagickDrawPoint #define MagickDrawPolygon GmMagickDrawPolygon #define MagickDrawPolyline GmMagickDrawPolyline #define MagickDrawPopClipPath GmMagickDrawPopClipPath #define MagickDrawPopDefs GmMagickDrawPopDefs #define MagickDrawPopGraphicContext GmMagickDrawPopGraphicContext #define MagickDrawPopPattern GmMagickDrawPopPattern #define MagickDrawPushClipPath GmMagickDrawPushClipPath #define MagickDrawPushDefs GmMagickDrawPushDefs #define MagickDrawPushGraphicContext GmMagickDrawPushGraphicContext #define MagickDrawPushPattern GmMagickDrawPushPattern #define MagickDrawRectangle GmMagickDrawRectangle #define MagickDrawRender GmMagickDrawRender #define MagickDrawRotate GmMagickDrawRotate #define MagickDrawRoundRectangle GmMagickDrawRoundRectangle #define MagickDrawScale GmMagickDrawScale #define MagickDrawSetClipPath GmMagickDrawSetClipPath #define MagickDrawSetClipRule GmMagickDrawSetClipRule #define MagickDrawSetClipUnits GmMagickDrawSetClipUnits #define MagickDrawSetFillColor GmMagickDrawSetFillColor #define MagickDrawSetFillOpacity GmMagickDrawSetFillOpacity #define MagickDrawSetFillPatternURL GmMagickDrawSetFillPatternURL #define MagickDrawSetFillRule GmMagickDrawSetFillRule #define MagickDrawSetFont GmMagickDrawSetFont #define MagickDrawSetFontFamily GmMagickDrawSetFontFamily #define MagickDrawSetFontSize GmMagickDrawSetFontSize #define MagickDrawSetFontStretch GmMagickDrawSetFontStretch #define MagickDrawSetFontStyle GmMagickDrawSetFontStyle #define MagickDrawSetFontWeight GmMagickDrawSetFontWeight #define MagickDrawSetGravity GmMagickDrawSetGravity #define MagickDrawSetStrokeAntialias GmMagickDrawSetStrokeAntialias #define MagickDrawSetStrokeColor GmMagickDrawSetStrokeColor #define MagickDrawSetStrokeDashArray GmMagickDrawSetStrokeDashArray #define MagickDrawSetStrokeDashOffset GmMagickDrawSetStrokeDashOffset #define MagickDrawSetStrokeLineCap GmMagickDrawSetStrokeLineCap #define MagickDrawSetStrokeLineJoin GmMagickDrawSetStrokeLineJoin #define MagickDrawSetStrokeMiterLimit GmMagickDrawSetStrokeMiterLimit #define MagickDrawSetStrokeOpacity GmMagickDrawSetStrokeOpacity #define MagickDrawSetStrokePatternURL GmMagickDrawSetStrokePatternURL #define MagickDrawSetStrokeWidth GmMagickDrawSetStrokeWidth #define MagickDrawSetTextAntialias GmMagickDrawSetTextAntialias #define MagickDrawSetTextDecoration GmMagickDrawSetTextDecoration #define MagickDrawSetTextEncoding GmMagickDrawSetTextEncoding #define MagickDrawSetTextUnderColor GmMagickDrawSetTextUnderColor #define MagickDrawSetViewbox GmMagickDrawSetViewbox #define MagickDrawSkewX GmMagickDrawSkewX #define MagickDrawSkewY GmMagickDrawSkewY #define MagickDrawTranslate GmMagickDrawTranslate #define MagickEdgeImage GmMagickEdgeImage #define MagickEmbossImage GmMagickEmbossImage #define MagickEnhanceImage GmMagickEnhanceImage #define MagickEqualizeImage GmMagickEqualizeImage #define MagickExtentImage GmMagickExtentImage #define MagickFlattenImages GmMagickFlattenImages #define MagickFlipImage GmMagickFlipImage #define MagickFlopImage GmMagickFlopImage #define MagickFrameImage GmMagickFrameImage #define MagickFxImage GmMagickFxImage #define MagickFxImageChannel GmMagickFxImageChannel #define MagickGammaImage GmMagickGammaImage #define MagickGammaImageChannel GmMagickGammaImageChannel #define MagickGetConfigureInfo GmMagickGetConfigureInfo #define MagickGetCopyright GmMagickGetCopyright #define MagickGetException GmMagickGetException #define MagickGetFilename GmMagickGetFilename #define MagickGetHomeURL GmMagickGetHomeURL #define MagickGetImage GmMagickGetImage #define MagickGetImageAttribute GmMagickGetImageAttribute #define MagickGetImageBackgroundColor GmMagickGetImageBackgroundColor #define MagickGetImageBluePrimary GmMagickGetImageBluePrimary #define MagickGetImageBorderColor GmMagickGetImageBorderColor #define MagickGetImageBoundingBox GmMagickGetImageBoundingBox #define MagickGetImageChannelDepth GmMagickGetImageChannelDepth #define MagickGetImageChannelExtrema GmMagickGetImageChannelExtrema #define MagickGetImageChannelMean GmMagickGetImageChannelMean #define MagickGetImageColormapColor GmMagickGetImageColormapColor #define MagickGetImageColors GmMagickGetImageColors #define MagickGetImageColorspace GmMagickGetImageColorspace #define MagickGetImageCompose GmMagickGetImageCompose #define MagickGetImageCompression GmMagickGetImageCompression #define MagickGetImageDelay GmMagickGetImageDelay #define MagickGetImageDepth GmMagickGetImageDepth #define MagickGetImageDispose GmMagickGetImageDispose #define MagickGetImageExtrema GmMagickGetImageExtrema #define MagickGetImageFilename GmMagickGetImageFilename #define MagickGetImageFormat GmMagickGetImageFormat #define MagickGetImageFuzz GmMagickGetImageFuzz #define MagickGetImageGamma GmMagickGetImageGamma #define MagickGetImageGeometry GmMagickGetImageGeometry #define MagickGetImageGravity GmMagickGetImageGravity #define MagickGetImageGreenPrimary GmMagickGetImageGreenPrimary #define MagickGetImageHeight GmMagickGetImageHeight #define MagickGetImageHistogram GmMagickGetImageHistogram #define MagickGetImageIndex GmMagickGetImageIndex #define MagickGetImageInterlaceScheme GmMagickGetImageInterlaceScheme #define MagickGetImageIterations GmMagickGetImageIterations #define MagickGetImageMatte GmMagickGetImageMatte #define MagickGetImageMatteColor GmMagickGetImageMatteColor #define MagickGetImageOrientation GmMagickGetImageOrientation #define MagickGetImagePage GmMagickGetImagePage #define MagickGetImagePixels GmMagickGetImagePixels #define MagickGetImageProfile GmMagickGetImageProfile #define MagickGetImageRedPrimary GmMagickGetImageRedPrimary #define MagickGetImageRenderingIntent GmMagickGetImageRenderingIntent #define MagickGetImageResolution GmMagickGetImageResolution #define MagickGetImageSavedType GmMagickGetImageSavedType #define MagickGetImageScene GmMagickGetImageScene #define MagickGetImageSignature GmMagickGetImageSignature #define MagickGetImageSize GmMagickGetImageSize #define MagickGetImageType GmMagickGetImageType #define MagickGetImageUnits GmMagickGetImageUnits #define MagickGetImageVirtualPixelMethod GmMagickGetImageVirtualPixelMethod #define MagickGetImageWhitePoint GmMagickGetImageWhitePoint #define MagickGetImageWidth GmMagickGetImageWidth #define MagickGetNumberImages GmMagickGetNumberImages #define MagickGetPackageName GmMagickGetPackageName #define MagickGetQuantumDepth GmMagickGetQuantumDepth #define MagickGetReleaseDate GmMagickGetReleaseDate #define MagickGetResourceLimit GmMagickGetResourceLimit #define MagickGetSamplingFactors GmMagickGetSamplingFactors #define MagickGetSize GmMagickGetSize #define MagickGetVersion GmMagickGetVersion #define MagickHaldClutImage GmMagickHaldClutImage #define MagickHasColormap GmMagickHasColormap #define MagickHasNextImage GmMagickHasNextImage #define MagickHasPreviousImage GmMagickHasPreviousImage #define MagickImplodeImage GmMagickImplodeImage #define MagickIsGrayImage GmMagickIsGrayImage #define MagickIsMonochromeImage GmMagickIsMonochromeImage #define MagickIsOpaqueImage GmMagickIsOpaqueImage #define MagickIsPaletteImage GmMagickIsPaletteImage #define MagickLabelImage GmMagickLabelImage #define MagickLevelImage GmMagickLevelImage #define MagickLevelImageChannel GmMagickLevelImageChannel #define MagickMagnifyImage GmMagickMagnifyImage #define MagickMapImage GmMagickMapImage #define MagickMatteFloodfillImage GmMagickMatteFloodfillImage #define MagickMedianFilterImage GmMagickMedianFilterImage #define MagickMinifyImage GmMagickMinifyImage #define MagickModulateImage GmMagickModulateImage #define MagickMontageImage GmMagickMontageImage #define MagickMorphImages GmMagickMorphImages #define MagickMosaicImages GmMagickMosaicImages #define MagickMotionBlurImage GmMagickMotionBlurImage #define MagickNegateImage GmMagickNegateImage #define MagickNegateImageChannel GmMagickNegateImageChannel #define MagickNewDrawingWand GmMagickNewDrawingWand #define MagickNextImage GmMagickNextImage #define MagickNormalizeImage GmMagickNormalizeImage #define MagickOilPaintImage GmMagickOilPaintImage #define MagickOpaqueImage GmMagickOpaqueImage #define MagickOperatorImageChannel GmMagickOperatorImageChannel #define MagickPingImage GmMagickPingImage #define MagickPreviewImages GmMagickPreviewImages #define MagickPreviousImage GmMagickPreviousImage #define MagickProfileImage GmMagickProfileImage #define MagickQuantizeImage GmMagickQuantizeImage #define MagickQuantizeImages GmMagickQuantizeImages #define MagickQueryFontMetrics GmMagickQueryFontMetrics #define MagickQueryFonts GmMagickQueryFonts #define MagickQueryFormats GmMagickQueryFormats #define MagickRadialBlurImage GmMagickRadialBlurImage #define MagickRaiseImage GmMagickRaiseImage #define MagickReadImage GmMagickReadImage #define MagickReadImageBlob GmMagickReadImageBlob #define MagickReadImageFile GmMagickReadImageFile #define MagickReduceNoiseImage GmMagickReduceNoiseImage #define MagickRelinquishMemory GmMagickRelinquishMemory #define MagickRemoveImage GmMagickRemoveImage #define MagickRemoveImageOption GmMagickRemoveImageOption #define MagickRemoveImageProfile GmMagickRemoveImageProfile #define MagickResampleImage GmMagickResampleImage #define MagickResetIterator GmMagickResetIterator #define MagickResizeImage GmMagickResizeImage #define MagickRollImage GmMagickRollImage #define MagickRotateImage GmMagickRotateImage #define MagickSampleImage GmMagickSampleImage #define MagickScaleImage GmMagickScaleImage #define MagickSeparateImageChannel GmMagickSeparateImageChannel #define MagickSetCompressionQuality GmMagickSetCompressionQuality #define MagickSetDepth GmMagickSetDepth #define MagickSetFilename GmMagickSetFilename #define MagickSetFormat GmMagickSetFormat #define MagickSetImage GmMagickSetImage #define MagickSetImageAttribute GmMagickSetImageAttribute #define MagickSetImageBackgroundColor GmMagickSetImageBackgroundColor #define MagickSetImageBluePrimary GmMagickSetImageBluePrimary #define MagickSetImageBorderColor GmMagickSetImageBorderColor #define MagickSetImageChannelDepth GmMagickSetImageChannelDepth #define MagickSetImageColormapColor GmMagickSetImageColormapColor #define MagickSetImageColorspace GmMagickSetImageColorspace #define MagickSetImageCompose GmMagickSetImageCompose #define MagickSetImageCompression GmMagickSetImageCompression #define MagickSetImageDelay GmMagickSetImageDelay #define MagickSetImageDepth GmMagickSetImageDepth #define MagickSetImageDispose GmMagickSetImageDispose #define MagickSetImageFilename GmMagickSetImageFilename #define MagickSetImageFormat GmMagickSetImageFormat #define MagickSetImageFuzz GmMagickSetImageFuzz #define MagickSetImageGamma GmMagickSetImageGamma #define MagickSetImageGeometry GmMagickSetImageGeometry #define MagickSetImageGravity GmMagickSetImageGravity #define MagickSetImageGreenPrimary GmMagickSetImageGreenPrimary #define MagickSetImageIndex GmMagickSetImageIndex #define MagickSetImageInterlaceScheme GmMagickSetImageInterlaceScheme #define MagickSetImageIterations GmMagickSetImageIterations #define MagickSetImageMatte GmMagickSetImageMatte #define MagickSetImageMatteColor GmMagickSetImageMatteColor #define MagickSetImageOption GmMagickSetImageOption #define MagickSetImageOrientation GmMagickSetImageOrientation #define MagickSetImagePage GmMagickSetImagePage #define MagickSetImagePixels GmMagickSetImagePixels #define MagickSetImageProfile GmMagickSetImageProfile #define MagickSetImageRedPrimary GmMagickSetImageRedPrimary #define MagickSetImageRenderingIntent GmMagickSetImageRenderingIntent #define MagickSetImageResolution GmMagickSetImageResolution #define MagickSetImageSavedType GmMagickSetImageSavedType #define MagickSetImageScene GmMagickSetImageScene #define MagickSetImageType GmMagickSetImageType #define MagickSetImageUnits GmMagickSetImageUnits #define MagickSetImageVirtualPixelMethod GmMagickSetImageVirtualPixelMethod #define MagickSetImageWhitePoint GmMagickSetImageWhitePoint #define MagickSetInterlaceScheme GmMagickSetInterlaceScheme #define MagickSetPassphrase GmMagickSetPassphrase #define MagickSetResolution GmMagickSetResolution #define MagickSetResolutionUnits GmMagickSetResolutionUnits #define MagickSetResourceLimit GmMagickSetResourceLimit #define MagickSetSamplingFactors GmMagickSetSamplingFactors #define MagickSetSize GmMagickSetSize #define MagickSharpenImage GmMagickSharpenImage #define MagickShaveImage GmMagickShaveImage #define MagickShearImage GmMagickShearImage #define MagickSolarizeImage GmMagickSolarizeImage #define MagickSpreadImage GmMagickSpreadImage #define MagickSteganoImage GmMagickSteganoImage #define MagickStereoImage GmMagickStereoImage #define MagickStripImage GmMagickStripImage #define MagickSwirlImage GmMagickSwirlImage #define MagickTextureImage GmMagickTextureImage #define MagickThresholdImage GmMagickThresholdImage #define MagickThresholdImageChannel GmMagickThresholdImageChannel #define MagickTintImage GmMagickTintImage #define MagickTransformImage GmMagickTransformImage #define MagickTransparentImage GmMagickTransparentImage #define MagickTrimImage GmMagickTrimImage #define MagickUnsharpMaskImage GmMagickUnsharpMaskImage #define MagickWaveImage GmMagickWaveImage #define MagickWhiteThresholdImage GmMagickWhiteThresholdImage #define MagickWriteImage GmMagickWriteImage #define MagickWriteImageBlob GmMagickWriteImageBlob #define MagickWriteImageFile GmMagickWriteImageFile #define MagickWriteImages GmMagickWriteImages #define MagickWriteImagesFile GmMagickWriteImagesFile #define NewMagickWand GmNewMagickWand #define NewPixelWand GmNewPixelWand #define NewPixelWands GmNewPixelWands #define PixelGetBlack GmPixelGetBlack #define PixelGetBlackQuantum GmPixelGetBlackQuantum #define PixelGetBlue GmPixelGetBlue #define PixelGetBlueQuantum GmPixelGetBlueQuantum #define PixelGetColorAsString GmPixelGetColorAsString #define PixelGetColorCount GmPixelGetColorCount #define PixelGetCyan GmPixelGetCyan #define PixelGetCyanQuantum GmPixelGetCyanQuantum #define PixelGetException GmPixelGetException #define PixelGetGreen GmPixelGetGreen #define PixelGetGreenQuantum GmPixelGetGreenQuantum #define PixelGetMagenta GmPixelGetMagenta #define PixelGetMagentaQuantum GmPixelGetMagentaQuantum #define PixelGetOpacity GmPixelGetOpacity #define PixelGetOpacityQuantum GmPixelGetOpacityQuantum #define PixelGetQuantumColor GmPixelGetQuantumColor #define PixelGetRed GmPixelGetRed #define PixelGetRedQuantum GmPixelGetRedQuantum #define PixelGetYellow GmPixelGetYellow #define PixelGetYellowQuantum GmPixelGetYellowQuantum #define PixelSetBlack GmPixelSetBlack #define PixelSetBlackQuantum GmPixelSetBlackQuantum #define PixelSetBlue GmPixelSetBlue #define PixelSetBlueQuantum GmPixelSetBlueQuantum #define PixelSetColor GmPixelSetColor #define PixelSetColorCount GmPixelSetColorCount #define PixelSetCyan GmPixelSetCyan #define PixelSetCyanQuantum GmPixelSetCyanQuantum #define PixelSetGreen GmPixelSetGreen #define PixelSetGreenQuantum GmPixelSetGreenQuantum #define PixelSetMagenta GmPixelSetMagenta #define PixelSetMagentaQuantum GmPixelSetMagentaQuantum #define PixelSetOpacity GmPixelSetOpacity #define PixelSetOpacityQuantum GmPixelSetOpacityQuantum #define PixelSetQuantumColor GmPixelSetQuantumColor #define PixelSetRed GmPixelSetRed #define PixelSetRedQuantum GmPixelSetRedQuantum #define PixelSetYellow GmPixelSetYellow #define PixelSetYellowQuantum GmPixelSetYellowQuantum #define QueryMagickColor GmQueryMagickColor #endif /* defined(PREFIX_MAGICK_SYMBOLS) */ #endif /* defined(_MAGICK_WAND_SYMBOLS_H) */ /* * Local Variables: * mode: c * c-basic-offset: 2 * fill-column: 78 * End: */ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/GraphicsMagick-1.3.35/config/delegates.mgk ================================================ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/GraphicsMagick-1.3.35/config/type-ghostscript.mgk ================================================ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/GraphicsMagick-1.3.35/config/type-solaris.mgk ================================================ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/GraphicsMagick-1.3.35/config/type-windows.mgk ================================================ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/GraphicsMagick-1.3.35/config/type.mgk ================================================ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/libGraphicsMagick.a ================================================ [File too large to display: 16.7 MB] ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/pkgconfig/GraphicsMagick++.pc ================================================ prefix=/root/pinwoodxu/GraphicsMagick-source/release exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include/GraphicsMagick Name: GraphicsMagick++ Version: 1.3.35 Description: C++ API for GraphicsMagick image processing library Requires: GraphicsMagick Libs: -lGraphicsMagick++ Cflags: ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/pkgconfig/GraphicsMagick.pc ================================================ prefix=/root/pinwoodxu/GraphicsMagick-source/release exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include/GraphicsMagick Name: GraphicsMagick Version: 1.3.35 Description: GraphicsMagick image processing library Libs: -L${libdir} -lGraphicsMagick Cflags: -I${includedir} ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/lib/pkgconfig/GraphicsMagickWand.pc ================================================ prefix=/root/pinwoodxu/GraphicsMagick-source/release exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include/GraphicsMagick Name: GraphicsMagickWand Version: 1.3.35 Description: GraphicsMagick Wand image processing library Requires: GraphicsMagick Libs: -lGraphicsMagickWand Cflags: ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/share/GraphicsMagick-1.3.35/config/colors.mgk ================================================ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/share/GraphicsMagick-1.3.35/config/log.mgk ================================================ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/share/GraphicsMagick-1.3.35/config/modules.mgk ================================================ ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/share/doc/GraphicsMagick/ChangeLog ================================================ 2020-02-23 Bob Friesenhahn * version.sh: Updates in preparation for the 1.3.35 release. Merge changes for 1.3.35 into GraphicsMagick-1_3 branch. * www/INSTALL-windows.rst: Update Windows installation and build documentation. 2020-02-22 Bob Friesenhahn * NEWS.txt: Update with News since previous release. * magick/magick.c (InitializeMagickSignalHandlers): This private implementation function is now a static function as it should have been. (InitializeMagickEx): New function which may be used in place of InitializeMagick() to initialize GraphicsMagick. This initialization function returns an error status value, may update a passed ExceptionInfo structure with error information, and provides an options parameter which supports simple bit-flags to tailor initialization. The signal handler registrations are skipped if the MAGICK_OPT_NO_SIGNAL_HANDER flag is set in the options. 2020-02-19 Bob Friesenhahn * magick/magick.c (MagickToMime): Add a MIME translation for "jpg". Issue reported by Pro Turm. 2020-02-18 Bob Friesenhahn * www/INSTALL-windows.rst: Add quoting to avoid losing backslashes in Windows paths. 2020-02-16 Bob Friesenhahn * magick/common.h: Add missing unsupported handling for some recently added GCC/Clang attributes. * magick/: Move all remaining private implementation code in public headers which is guarded by MAGICK_IMPLEMENTATION into private headers, which are never installed. 2020-02-15 Bob Friesenhahn * coders/tiff.c (WriteTIFFImage): Evidence suggests that large strip sizes improve performance by reducing the number of I/Os. The defaults suggested by libtiff are way to small for today's images and computers. Default TIFF strip sizes so that each uncompressed strip consumes up to 1MiB of memory, or 4MiB for FAX oriented codecs, or based on LZMA compression level when using LZMA compression. The default size may be adjusted via the TIFF_BYTES_PER_STRIP preprocessor definition. 2020-02-09 Fojtik Jaroslav * coders/wpg.c ZeroFillMissing data will never been triggered when y>=image->rows. 2020-02-09 Bob Friesenhahn * magick/render.c (DrawImage): Limit pattern dimensions by LONG_MAX rather than ULONG_MAX since this seems more likely to avoid arithmetic overflows later on. 2020-02-09 Fojtik Jaroslav * coders/wpg.c Check for exception in image. 2020-02-09 Bob Friesenhahn * magick/command.c (VersionCommand): Add Google perftools tcmalloc to the available feature support. * www/INSTALL-unix.rst: Include some information about building with MSYS2. * coders/png.c (ReadOnePNGImage): Eliminate compilation warnings about signed/unsigned comparisons. * magick/image.c: Remove private global string constants, and one private global unsigned long constant, from the library ABI. Since the global constants were declared via a private header and only used within the GraphicsMagick build, removing these does not impact the public ABI. The globals removed are BackgroundColor, BorderColor, DefaultTileFrame, DefaultTileGeometry, DefaultTileLabel, ForegroundColor, HighlightColor, MatteColor, PSDensityGeometry, PSPageGeometry, and DefaultCompressionQuality. 2020-02-08 Bob Friesenhahn * magick/render.c (DrawImage): Apply draconian pattern specification offset and dimension validations. Hopefully there is no impact to usability. If so please report it as a bug. Fixes oss-fuzz 20586 "graphicsmagick:coder_MVG_fuzzer: Integer-overflow in DrawPolygonPrimitive". * coders/svg.c (ReadSVGImage): Fix dereference of NULL pointer when stopping image timer. 2020-02-06 Bob Friesenhahn * coders/pict.c (DecodeImage): Allocate extra scanline memory to allow small RLE overrun. Fixes oss-fuzz 20271 "graphicsmagick:coder_PICT_fuzzer: Heap-buffer-overflow in ExpandBuffer" and 20272 "graphicsmagick:coder_PICT_fuzzer: Heap-buffer-overflow in DecodeImage". * PerlMagick/t/wmf/read.t: Update WMF reference images. Relax test requirements for ski.wmf. * locale/C.mgk: Correct error message associated with "UnsupportedNumberOfRows". Patch was submitted by Thorsten Alteholz via private email on 2020-02-05. 2020-02-04 Bob Friesenhahn * coders/topol.c: Include magick/magick_endian.h. 2020-02-03 Bob Friesenhahn * magick, coders, wand: Added copious casts to avoid possible integer overflows in the Microsoft Windows 64-bit build, where sizeof(long) < sizeof(size_t). 2020-01-26 Bob Friesenhahn * magick/render.h ("PrimitiveInfo"): Change PrimitiveInfo coordinates from type 'unsigned long' to 'size_t'. 2020-01-24 Bob Friesenhahn * magick/gradient.c (GradientImage): Warnings reduction, plus note about incorrect diagonal gradients math. 2020-01-20 Fojtik Jaroslav * VisualMagick\configure\configure.cpp Option /arch:SSE2 is available only for 32 bit build. 2020-01-19 Bob Friesenhahn * coders/pcd.c (DecodeImage): Assure that pcd_length gets initialized with something. * Magick++/lib/Options.cpp (strokeDashArray): Add needless check for _drawInfo->dash_pattern null in order to make static analysis happy. * magick/render.c (DestroyPolygonInfo): Make sure to not dereference a null edges pointer. * coders/pdb.c (WritePDBImage): Make sure that null comment value is not dereferenced. * coders/vid.c (ReadVIDImage): Make sure that ThrowVIDReaderException does not dereference a null pointer. * magick/quantize.c (ClassifyImageColors): Fix error handling so a null pointer won't be consumed after a memory allocation failure. Changed the location of some variable declarations and added some comments. 2020-01-18 Bob Friesenhahn * coders/caption.c (ReadCAPTIONImage): Assure that metrics are initialized. * magick/pixel_cache.c (DestroyThreadViewSet): Check if views pointer is not null before destroying views. * coders/xpm.c (ReadXPMImage): Properly detect the case where the XPM colormap is not fully initialized. * coders/pict.c (DecodeImage): Fix heap buffer over-reads. Fixes oss-fuzz issue 20053 "graphicsmagick:coder_PICT_fuzzer: Heap-buffer-overflow in ExpandBuffer" and oss-fuzz issue 20048 "graphicsmagick:coder_PICT_fuzzer: Heap-buffer-overflow in DecodeImage". Both of these oss-fuzz issues appeared due to recent changes since the last release. * coders/meta.c (WriteMETAImage): Assure that 'iptc_offset' is initialized and valid. * coders/jpeg.c (ReadJPEGImage): Assure that evaluating the embedded profile length does not suffer from undefined behavior. 2020-01-12 Bob Friesenhahn * magick/render.c (DrawImage): Add more MVG parser validations. 2020-01-11 Bob Friesenhahn * coders/histogram.c (WriteHISTOGRAMImage): Histogram coder was relying on the previously removed '@' file inclusion feature to insert the histogram comment text. Write a PseudoClass MIFF image with RLE compression. Fixes SourceForge issue #622 "Histogram produces incorrect color table attribute ". * magick/pixel_cache.c (ModifyCache): Re-open the pixel cache if the cache rows/columns do not match the owning image rows/columns. * magick/transform.c (TransformImage): TransformImage now returns a MagickPassFail return status value rather than void. * coders/pict.c (ReadPICTImage): Fix some over-strict validations which were preventing some PICT files which were previously read successfully from being accepted. Fix problems which occurred when the clipping rectangle changed the image size. Improve reading embedded JPEG blobs. Now successfully reads all raster PICT files I have available. 2020-01-08 Bob Friesenhahn * coders/pict.c (ReadPICTImage): Be more strict about PICT rectangle by treating rectangle dimensions as if they are a 16-bit signed type and not allowing negative values. Avoid GCC warnings which sprung up similar to "warning: comparison is always false due to limited range of data type". 2020-01-05 Bob Friesenhahn * coders/sfw.c (ReadSFWImage): Restore a DestroyImage() statement which was accidentally deleted by recent edits. Fixes oss-fuzz "Issue 19819 in oss-fuzz: graphicsmagick:coder_SFW_fuzzer: Indirect-leak in AllocateImage". * coders/png.c (WriteOneJNGImage): Detect when JPEG encoder has failed, and throw exception. Fix image dimension limit validations. Stop discarding exception report. Fixes SourceForge bug #621 "Assertion in WriteBlob at magick/blob.c:4937" which was reported by Suhwan Song. * coders/pict.c (WritePICTImage): Eliminating small buffer overrun when run-length encoding pixels. Fixes SourceForge bug #620 "heap-buffer-overflow in EncodeImage at coders/pict.c:1114" which was reported by Suhwan Song. * coders/logo.c (ReadLOGOImage): PATTERN error handling was incomplete. Add appropriate error handling. (ReadLOGOImage): Switch to using ConstituteTextureImage() rather than TextureImage() since it is more appropriate for this purpose. (ReadLOGOImage): Oops! Accidental change of behavior. When size is not supplied, simply return the pattern image. 2020-01-04 Bob Friesenhahn * coders/*.c (ReadFOOImage): Stop image timer just before returning from reader so that reported timings are correct when used in the future. 2020-01-03 Bob Friesenhahn * magick/timer.c (StartTimer): Expose previously existing StartTimer() function. (StopTimer): Expose previously existing StartTimer() function. * magick/constitute.c (WriteImage): Don't over-write time-stamp when output is to INFO format. 2020-01-03 Fojtik Jaroslav * VisualMagick\configure\configure.exe: Should not depend on mfcr90.dll. It is too bad when end user cannot run this tool because of missing DLL. * VisualMagick\configure\configure.cpp Make speed optimisation as default option. * VisualMagick\configure\configure.vcproj Give different filename to debug build to avoid accidental committing debug build to repository. 2020-01-01 Bob Friesenhahn * coders/dpx.c (GenerateDPXTimeStamp): Use reentrant localtime_r() function if it is available. * magick/log.c (LogMagickEventList): Use reentrant localtime_r() function if it is available. * coders/cineon.c (GenerateCineonTimeStamp): Use reentrant localtime_r() function if it is available. * coders/mat.c (WriteMATLABImage): Use reentrant localtime_r() function if it is available. * coders/pdf.c (WritePDFImage): Use reentrant localtime_r() function if it is available. * coders/ps.c (WritePSImage): Use reentrant ctime_r() function if it is available. * coders/ps2.c (WritePS2Image): Use reentrant ctime_r() function if it is available. * coders/ps3.c (WritePS3Image): Use reentrant ctime_r() function if it is available. * configure.ac: Test for getpwnam_r(). * magick/utility.c (ExpandFilename): Use reentrant getpwnam_r() function if it is available. * magick/magick.c (InitializeMagickSignalHandlers): Use the normal termination signal handler for SIGXCPU and SIGXFSZ so that ulimit or setrlimit(2) may be used to apply CPU (RLIMIT_CPU) and output file size (RLIMIT_FSIZE) limits with the normal cleanup, and without dumping core. Note that any output files currently being written may be truncated and files being written by external programs (e.g. Ghostscript) might be left behind unless they are to a temporary file assigned by GraphicsMagick. * coders/xpm.c (ReadXPMImage): Promote a color-lookup warning to an error. * coders/xc.c (ReadXCImage): Promote a color-lookup warning to an error. * coders/null.c (ReadNULLImage): Promote a color-lookup warning to an error. * Makefile.am: Rotate ChangeLogs for the new year. * coders/gradient.c (ReadGRADIENTImage): Promote a color-lookup warning to an error. ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/share/doc/GraphicsMagick/ChangeLog.2001 ================================================ 2001-12-28 Leonard Rosenthol * Even more features and options were added to conjure * Added CropBox support to PDF writer 2001-12-26 Leonard Rosenthol * Conjure now supports having a list of files for the script to process being passed on the command line. * More features and options were added to conjure 2001-12-25 Leonard Rosenthol * Made a huge number of improvements to conjure. It now supports over 15 different commands for manipulating your images. 2001-12-24 Cristy * Started a new scripting language utility, conjure. 2001-12-20 Cristy * Display the search path in the event a utility cannot find a particular configuration file (thanks to billr@corbis.com) 2001-12-14 Leonard Rosenthol * Fixed some bugs in the new composite operators. 2001-12-14 Bob Friesenhahn * Added native BLOB support to coders/wmf.c. 2001-12-13 Leonard Rosenthol * Added new composite operators to support PSD/XCF layer compositing: NoCompositeOp, DarkenCompositeOp, LightenCompositeOp, HueCompositeOp, SaturateCompositeOp, ValueCompositeOp, ColorizeCompositeOp, LuminizeCompositeOp, ScreenCompositeOp, OverlayCompositeOp. * Modified the PSD coder to set the appropriate composite operator. * Modified the XCF coder to set the appropriate composite operator. 2001-12-10 Cristy * Removed the flatten option from ImageInfo. * Added new compose member to ImageInfo that defines which of the composite operators to use when flattening an image. 2001-12-09 Leonard Rosenthol * Added new member to ImageInfo, flatten, used by PSD and XCF to determine whether to flatten an image when read. * PSD and XCF now respect image_info->flatten. * Fixed bug in XCF loader when loading layered image as layers. * Modified the convert program to set image_info->flatten if -flatten is specified; we still call FlattenImages for other formats that don't respect image_info->flatten. * Modified Magick++'s Image class to support image_info->flatten. 2001-12-08 Leonard Rosenthol * Improvements to the Photoshop (PSD) coder: 1) added support for Duotone images loaded as grayscale as per PSD docs; and 2) added option to composite layers when reading respects layer visibility setting. 2001-12-07 Cristy * -dissolve wasn't working for the composite program (thanks to Rick Manbry). * DCM coder failed to read a valid DCM image file. 2001-12-06 Cristy * Stream buffer was not being freed in ReadStream(). 2001-12-05 Cristy * Corrected bias when downsizing an image with ResizeImage(). 2001-11-25 Cristy * AcquireImagePixels() can accept (x,y) outside the image area (e.g. AcquireImagePixels(image,-3,-3,7,7,exception)). 2001-11-22 Cristy * Added limited SVG gradient support. 2001-11-21 Cristy * Added API method, PingBlob(). 2001-11-14 Cristy * Moved a few pixel related defines (e.g. Downscale()) to a corresponding method to enforce strong type checking at compile time. 2001-11-12 Cristy * Previously ImageMagick did not write 8-bit ASCII PPM/PGM files when QuantumDepth == 16. * Added 'id' as an image attribute in PerlMagick (returns ImageMagick registry ID). 2001-11-10 Cristy * Added SVG pattern support. * Changed default background color to none. 2001-11-06 Cristy * Added support of reading and writing 16-bit raw PPM/PGM files. 2001-11-05 Cristy * Added -level to convert/mogrify (suggested by mericson@phillynews.kom). 2001-11-04 Cristy * -shadow/-shade were not distiguished. 2001-11-03 Bob Friesenhahn * PerlMagick/Makefile.PL.in: Install PerlMagick using ImageMagick's configure prefix. 2001-11-02 Cristy * Typecast offset to unsigned long in coders/pdf.c. 2001-11-01 Cristy * Convert's -flatten, -average, etc. failed with an assert error. 2001-10-30 Cristy * Added support for On-the-air bitmap. 2001-09-29 Glenn * When the delay setting for an image is greater than 4cs, duplicate frames are inserted to achieve the desired delay while creating MPEG files (contributed by Lawrence Livermore National Laboratory (LLNL)). 2001-10-29 Cristy * ImageMagick now has a registry for storing image blobs. 2001-10-26 Cristy * Added VMS patches (thanks to Jouk Jansen). 2001-10-25 Bob Friesenhahn * Fixed parsing bug for decorate #FFFFFF. 2001-10-22 Bob Friesenhahn * Added tests for mpeg2 library to configure. 2001-10-22 Cristy * Added a MPEG coder module. * Added ImageType member to the image_info structure (suggested by Glenn) 2001-10-21 Bob Friesenhahn * Eliminated libMagick.so dependency on libxml by not listing -lxml when doing modules link. 2001-10-18 Cristy * Eliminated the libMagick.so dependancy on libtiff by moving Huffman2DEncodeImage() from magick/compress.c to coders/pdf.c, coders/ps2.c and coders/ps3.c (suggested by Bob Friesenhahn). This change has the side-effect of elminating dependency on libpng and libjpeg as well (which libtiff may depend on). 2001-10-16 Cristy * Convert now supports -channel {Cyan,Magenta,Yellow,Black}. 2001-10-14 Bob Friesenhahn * coders/wmf.c updated for libwmf 0.2. Plenty of bugs remain within. 2001-10-11 Cristy * QueryFontMetrics() of PerlMagick now recognizes embedded special characters (e.g. %h). 2001-10-10 Cristy * Fixed seg-fault for PingImage() on a JP2 image file. 2001-10-07 Cristy * CloneImage() now uses a referenced counted pixel cache. 2001-10-05 Cristy * Added AcquireImagePixels() method. * Changed the formal parameter from Image * to const Image * for a number of methods (e.g. ZoomImage()). * Added ExceptionInfo parameter to DispatchImage(). 2001-10-05 Bob Friesenhahn * Find libxml headers under Debian Linux (bug ID 921). 2001-10-02 Cristy * Fixed assertion error on drawing stroked text. 2001-10-01 Cristy * Added blob test to the PerlMagick test suite. 2001-09-30 Cristy * switched strcpy to strncpy to help protect against buffer overflow. * ltdl.c passed int reference but a long was needed; caused a fault on Solaris 64-bit compiles. 2001-09-25 Cristy * Removed most lint complaints from the source. * strtod() returns different results on Linux and Solaris for 0x13. * Added a MATLAB encoder contributed by Jaroslav Fojtik. 2001-09-21 Cristy * Replaced TemporaryFilename() with UniqueImageFilename(). * ImageMagick CORE API is now 64-bit clean. 2001-09-20 Cristy * Fixed svg.c to accept a viewbox with a negative offset. 2001-09-15 Cristy * Surveying the code for 64-bit compatibility. * The cloned colormap was too small (reported by Glenn). * A blob was being unmapped more than once for multi-frame images. 2001-09-12 Cristy * Text drawing now handles UTF8-encoding. * Off-by-one GetImagePixels() fix in draw.c * PingImage() now reports attributes for all images in an image sequence. 2001-09-10 Bob Friesenhahn * magick/image.h: Rename QuantumLeap define to QuantumDepth. QuantumDepth is set to the values 8 or 16, depending on user configuration option. 2001-09-09 Cristy * Updated PerlMagick signatures to reflect new message digest algorithm. 2001-09-08 Cristy * ImageMagick defaults to 16-bit quantum. Set QuantumMagick for 8-bit. * Changed image->blob from BlobInfo to BlobInfo* so the Image structure size is not dependent on the large-file preprocessor defines. 2001-09-07 Cristy * Added -background to convert program usage text. * DispatchImage() now properly handles grayscale images. 2001-09-01 Glenn * The compression quality setting is now recognized when creating MPEG images (contributed by Lawrence Livermore National Laboratory (LLNL)). ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/share/doc/GraphicsMagick/ChangeLog.2002 ================================================ 2002-12-31 Cristy * magick/command.c: Do not quantize CMYK (bug fix). * magick/render.c: Ensure that stroke is not drawn wider than requested when antialiasing is disabled (bug fix). 2002-12-30 Bob Friesenhahn * magick/image.c: For TransformRGBImage() and RGBTransformImage() round values to int when creating tables rather than using scaling to avoid rounding. 2002-12-30 Bob Friesenhahn * coders/png.c: Fixed compile problems. * magick/image.c: SyncImage() performance optimizations. * TransformRGBImage() cleanup/enhancements. Some rounding issues remain. * RGBTransformImage() cleanup/enhancements. Some rounding issues remain. 2002-12-24 Glenn Randers-Pehrson * BUGFIX: Fixed bug, introduced on 12/18/02, in which a misplaced "}" caused an assertion failure after reading any opaque JNG image. * Added CloseBlob before returning a NULL JNG image. * Merged png.c with IM-5.5.3-1, including a seemingly pointless rename of SaveImageText string to SaveImageTag. 2002-12-27 Bob Friesenhahn * magick/image.c: Optimized gray x, y, z, tables creation in RGBTransformImage(). 2002-12-27 Cristy * coders/pcd.c: IsPCDImage() fix offset to test header magic. * coders/pcd.c: Ensure that blob is closed on error. * coders (all): Pass image->colorspace to TransformRGBImage() * magick (animate.c, command.c, display.c, image.c, nt_feature.c) Pass image->colorspace to TransformRGBImage(). * magick/nt_feature.c: Ensure that image is RGB prior to transfer to HBITMAP. 2002-12-26 Bob Friesenhahn * magick/image.c: Re-worked TransformRGBImage() again so that it is now smoking fast for Q:8 and Q:16. Changed lookup tables, and all per-pixel transforms to use only integer arithmetic. A pre-multiplication scheme is used which should actually improve the quantization error over using double arithmetic. It is actually possible to improve Q:32 performance a bit more but is it worth the effort? 2002-12-24 Bob Friesenhahn * magick/image.c: Implemented logging for TransformRGBImage() and RGBTransformImage(). 2002-12-24 Glenn Randers-Pehrson * The png codec would close the blob twice (second time raising an assertion) if a libpng error was encountered. * Sometimes the PNG writer would receive an invalid bit depth from CompositeImages(); this is now ignored. 2002-12-23 Bob Friesenhahn * magick/image.c: Re-wrote TransformRGBImage() so that it does not penalize a Q:8 build. The function should be faster now, but no timings have been made to verify that. 2002-12-21 Glenn Randers-Pehrson * Elimimated unused transparent_pixel array in png.c. * Reverted to incrementing loops in bmp.c where the counter "i" is used in the loop. 2002-12-20 Bob Friesenhahn * magick/command.c: Update MogrifyImage() so that gm is 9X faster when transforming a color image to grayscale. 2002-12-19 Bob Friesenhahn * Updated coders to use VerifyColormapIndex macro rather than slow ConstrainColormapIndex() function. * magick/constitute.c: Trial use of VerifyColormapIndex in PushImagePixels() IndexQuantum case. 2002-12-19 Bob Friesenhahn * magick/color.c: Added VerifyColormapIndex macro to verify range of color index without a function call. * coders/bmp.c: Updated to use VerifyColormapIndex macro. 2002-12-19 Bob Friesenhahn * coders/bmp.c: Sped up RLE expansion and sped up byte-size PseudoColor scanline conversion. Results in 50% speed-up when running on SPARC. 2002-12-18 Bob Friesenhahn * utilities: Removed legacy ImageMagick utilities which have been rolled up into gm.c/command.c. 2002-12-18 Bob Friesenhahn * PerlMagick/Magick.xs: Fixed FormatString() format problems identified by the compiler. 2002-12-18 Bob Friesenhahn * magick/image.h: Moved function prototypes for functions implemented in code modules other than image.c to seperate header files with names based on the implementation files. 2002-12-17 Bob Friesenhahn * magick/enhance.c: Report appropriate message while leveling image. 2002-12-18 Glenn Randers-Pehrson * Sync png.c and fx.c with IM-5.5.3. "gm convert -list format" now includes zlib version info among the PNG info. * ConvolveImage() logs kernel info as a "Transform" debug event. * ReadJNGImage() now skips decoding JPEG subimage when "pinging" 2002-12-17 Cristy * SVG element `stroke-dasharray: 0` no longer causes a segmentation fault. 2002-12-17 Cristy * CoaleseceImage() properly handles a dispose method of BackgroundDispose. 2002-12-17 Bob Friesenhahn * configure.ac: Updated to substitute for @GMDelegate@. * magick/effect.c: Changed AdaptiveThresholdImage offset to double so that it works with QuantumDepth=32. Thanks to Glenn for pointing out this problem. * magick/image.c: Adapted to AdaptiveThresholdImage API change. * magick/image.h: Annotated global constants and functions with the name of the source file where they are implemented. This is in preparation to break up image.h into multiple header files to diminish unnecessary header dependencies. * coders/delegates.mgk.in: Updated to use @GMDelegate@ definition and `gm` program rather than ImageMagick utility names. * PerlMagick/t/read.t: Converted gradient test (which was not working at all) to compare with a reference image. * PerlMagick/t/jpeg/read.t: Re-wrote to compare with reference image. * PerlMagick/t/jpeg/write.t: Re-wrote to compare with reference image. * magick/image.c, magick/command.c: Moved MogrifyImage and MogrifyImages from image.c to command.c in order to diminish unnecessary inter-object coupling. Only functions in command.c should use MogrifyImage or MogrifyImages. Some work remains to accomplish that. 2002-12-16 Cristy * coders/jpeg.c: Add missing break statements to fix colorspace handling when image colorspace is CMYKColorspace or YCbCrColorspace. * magick/decorate.c: Cast to double in calculation. * magick/enhance.c: Tweaks to equalization map calculation to (hopefully) provide more consistent results. * magick/resize.c: Use type double rather than long for minify weighting constants. 2002-12-13 Bob Friesenhahn * coders/image.h: AdaptiveThresholdImage offset must be a signed type. 2002-12-13 Bob Friesenhahn * Re-wrote PerlMagick filter.t tests so that they all compare results with reference images rather than compare signatures. This makes the tests easier to maintain and also makes it easier to find errors in ImageMagick. 2002-12-13 Bob Friesenhahn * magick/command.c: Warnings reduction * magick/list.c: Warnings reduction 2002-12-13 Bob Friesenhahn * Updated PerlMagick tests for Emboss, Equalize, Gamma, Normalize, OilPaint, and Gradient so that they pass at Q:8 under Windows. * Updated PerlMagick tests for Emboss, and reading WMF, so that they pass at Q:16 under Windows. * VisualMagick\installer\ImageMagick-16.iss: Ported over from ImageMagick-8.iss and verified. 2002-12-13 Bob Friesenhahn * Major smashing of ImageMagick to GraphicsMagick in .txt files and .html files. * ImageMagick.html: Renamed to index.html. * www/ImageMagick.html: Renamed to www/GraphicsMagick.html 2002-12-12 Bob Friesenhahn * magick/list.c: Added GetFirstImageInList() function. * magick/list.c: Added GetLastImageInList() function. * coders/pcd.c: Re-implemented image tile labeling to avoid use of MogrifyImages(). 2002-12-12 Bob Friesenhahn * Added `commit` shell script to CVS for those who chose to use it. 2002-12-12 Bob Friesenhahn * magick/magick.c: Ensure that operating system call error return values are never used in resource limit calculation. 2002-12-12 William Radcliffe * magick/magick.c: Fixed bugs in InitializeMagick, but I also heavily commented the code so show what it seems to be doing. It appears broken and needs testing on all platforms. Toward that end, I added Log events so that we can see what it is doing. 2002-12-12 William Radcliffe * utilities/gm.c: Fixes a crashing bug in gm.c caused by an attempt to free a bad pointer. Added comments to the code that explain why this happens so that future developers don't fall into the same trap. * win2k/IMDisplay/IMDisplay.rc Modified some of the string resources that define supported file formats that were in error. One example was eps with had a *.eps in the string instead of just .eps. This caused the document class to ASSERT under the debug build. 2002-12-12 Bob Friesenhahn * Enable the module loading code for shared/DLL builds regardless of whether the build is a "modules" build. This allows users to add their own modules without requiring the use of a special "modules" build. 2002-12-11 Bob Friesenhahn * magick/image.h: Backed out arbitrary name change from ChannelThresholdImage() to ThresholdImageChannel() that snuck in from Cristy's image.h changes. 2002-12-11 Cristy * coders/psd.c: Reference cloned image Blob (not sure why needed but must be important). 2002-12-11 Cristy * magick/enhance.c: Fixed LevelImage() to accept percent black/white points (.i.e. 90%). * magick/enhance.c: Added LevelImageChannel(). * magick/enhance.c: Improved Q:8 performance of color transformations (e.g. for Gamma) which are based on a mapping array. * coders/pcl.c: Fixed PCL coder to output proper color PCL instructions. 2002-12-09 Bob Friesenhahn * magick/image.c: Disabled SetImageInfo() code which uses GetImageMagick() to test file magic via Is* methods so that we can learn if eliminating use of these tests causes any ill effects. 2002-12-09 William Radcliffe * Moved xtrn.c from contrib area into coders area so that it can be used from within the COM object. This is windows only code that provides a back door way for the COM object to have data read or written into VB arrays. 2002-12-08 Bob Friesenhahn * magick/mac.c: Merged in fixes from ImageMagick version. * magick/magick.mgk: Merged in fixes from ImageMagick version. 2002-12-07 Bob Friesenhahn * magick/image.c: Fix ChannelImage() so that it does not destroy CMYK(A) channels by forcing RGB. 2002-12-06 Bob Friesenhahn * magick/version.h: Changed to release 1.0.0. * magick/nt_base.c: Changed "ImageMagick" to "GraphicsMagick" so registry lookups work for GraphicsMagick. Probably should be configured via a magick_config.h define. * VisualMagick/installer/ImageMagick-8.iss: Changed for GraphicsMagick. * utilities/conjure.c: Fix unterminated comment. 2002-12-06 William Radcliffe * coders/jpeg.c: Modification of JPEG APP1 detection logic to name EXIF and XMP profiles as EXIF and XMP instead of APP1. THe current algorithm is brute force. * coders/meta.c: Modification deal with EXIF and XMP requests so that you can ask for these blobs specifically if they exist. * coders/pdf.c,ps.c,ps2.c,ps3.c: Cristy bug fixes to eliminate redundant file access checking and fix embedded JPEG support. * magick/random.c: Upgraded this to match current Cristy code. The upgrade is to support more robust temporary filenames in another change to this in utility.c however, I have not upgraded this code yet because I don't understand it well enough. 2002-12-06 Bob Friesenhahn * Added build support for utilities/gm.c 2002-12-06 Glenn Randers-Pehrson * Relocated animate, conjure, display, and import functions into command.c. * Added utilities/gm.c; gm is a driver for all of the utility functions (animate, composite, conjure, convert, display, identify, import, mongrify, and montage), which are now run with "gm convert [convert_options]", "gm identify [identify_options]", etc. 2002-12-05 Bob Friesenhahn * coders/pdf.c: Remove bogus code for handling temporary file. 2002-12-04 Bob Friesenhahn * Updated to Autoconf 2.57. * Install libraries as -lGraphicsMagick and -lGraphicsMagick++ under Unix. * Install headers under ${PREFIX}/include/GraphicsMagick under Unix. * Update *-config scripts to produce correct library and include statements. * Update PerlMagick to use correct library and include statements. 2002-12-04 William Radcliffe * contrib/win32/ATL7/ImageMagickObject/ImageMagickObject.cpp: Fixed serious problem with not installing custom error and warning handlers in the new version of the COM object. 2002-12-04 William Radcliffe * magick/constitute.c: Pass exceptions on write up into the exception structure passed into the WriteImages function. 2002-12-04 William Radcliffe * magick/image.c: Added orphan image functionality changes that are purported to fix bugs in PDF and PS coders. 2002-12-04 William Radcliffe * magick/locale.c: Hard coded the locale as per Cristy fix, but also added a comment and disabled useless code. 2002-12-04 William Radcliffe * VisualMagick/bin/magic.mgk: Added JNG as per the copy in magick subdirectory. 2002-12-04 William Radcliffe * tiff/libtiff/tiff.h: Minor changes to make reading older Photoshop TIFF files spew fewer warnings. 2002-12-04 Glenn Randers-Pehrson * Optimized ConvolveImage() by normalizing the kernel values instead of normalizing the pixels. 2002-12-01 Glenn Randers-Pehrson * www/formats.html: Add JNG and fix libpng links. 2002-12-01 Bob Friesenhahn * ChangeLog: Updated this ChangeLog to use the format prescribed by the GNU coding standards. 2002-12-01 Glenn Randers-Pehrson * coders/png.c: Use PNG_SETJMP_NOT_THREAD_SAFE to indicate that the C library's setjmp() API is not thread safe. * Fix use of image_info->blob. 2002-11-19 Bob Friesenhahn * Set up new CVS repository for GraphicsMagick based on current ImageMagick 5.5.2 (pre-release) sources. 2002-11-15 Bob Friesenhahn * Flashpix library now uses C++ standard and iostreams rather than legacy new and iostreams. 2002-11-15 Cristy * The blob methods were enhanced to use GZip or BZip API methods to compress/uncompress images (previously the external programs gunzip or bunzip2 were used). 2002-11-15 Bob Friesenhahn * Update to Autoconf 2.56 2002-11-14 Bob Friesenhahn * Update to Autoconf 2.55 2002-11-13 Bob Friesenhahn * Moved coder Register/Unregister method prototypes to static.h since they are only needed by static.c. * Removed defunct HDF and libmpeg2 support since it was confusing to users. 2002-11-11 Bob Friesenhahn * coders/wmf.c: Set white background of embedded bitmaps to transparent if the image background is a texture image, not-white, or non-opaque. This improves the output when the WMF is rendered on a non-default background. 2002-11-10 Bob Friesenhahn * Updated Windows CVS to FreeType 2.1.2. 2002-11-09 Bob Friesenhahn * Updated Windows CVS to Jasper 1.600.0. 2002-11-09 Bob Friesenhahn * Verify sanity of sysconf(_SC_PAGE_SIZE) and sysconf(_SC_PHYS_PAGES) before using their values. 2002-11-05 Bob Friesenhahn * Modified IMdisplay so that larger images may be loaded (primarily limited by Windows bitmap size limits). * Added some more file types (EPS, GIF, MIFF, SVG, & WMF) to IMdisplay's file open list. * The list management methods were given more meaningful names. 2002-11-04 Bob Friesenhahn * Modified IMdisplay so that Magick++ Images are stored by value rather than via pointer. * IMdisplay now uses minify(), magnify(), and zoom() methods where appropriate. 2002-11-04 Cristy * Quantizing a DirectClass image with less than 256 unique colors is no longer lossy. * Transparent TGA images had incorrect opacity values. 2002-10-31 Bob Friesenhahn * Added configure test for compiler __func__ support (HAS___func__). * Added configure test for ftime(). 2002-10-31 Leonard Rosenthol * CMYK + alpha layered PSD files now correctly read! 2002-10-30 Leonard Rosenthol * ReadPSDImage() is now fully instrumented with logging * Fixed long standing bug in ReadPSDImage, so it no longer returns an extra layer 2002-10-29 Glenn Randers-Pehrson * Added three output formats: PNG24 (24-bit RGB PNG, opaque only), PNG32 32-bit (RGBA PNG, semitransparency OK), and PNG8 (8-bit indexed PNG, binary transparency only). 2002-10-27 Bob Friesenhahn * coders/vid.c: Modified to be 10X faster for large images and to take advantage of JPEG size optimizations. 2002-10-27 Bob Friesenhahn * magick/xwindow.c: Optimize loading of TrueColor images with gamma = 1.0. 2002-10-27 Bob Friesenhahn * coders/wmf.c: Added logging facilities. 2002-10-27 Bob Friesenhahn * display.c: removed unnecessary SignatureImage() calls which dramatically slowed down loading images and quiting the program. * xwindow.c: optimized image size reduction for the case where the target size is a small fraction of the original size. This makes creation of display's panner and thumbnail images tremendously faster, with no noticeable degradation of thumbnail quality. 2002-10-21 Bob Friesenhahn * Added Windows95 define to VisualMagick magick_config.h to disable use of features not available under Windows '95 2002-10-21 Cristy * Added large file pixel cache support for Windows NT. 2002-10-21 Leonard Rosenthol * PDF coder no longer uses ASCII85 encoding with TIFF for MUCH smaller files! * Cleaned up a few other things in PDF coder. 2002-10-19 Bob Friesenhahn * Updated to Automake 1.7.1. 2002-10-18 Cristy * PingBlob() improperly set the length of BlobInfo to zero. * Fixed Ping() memory leak in PerlMagick. * Fixed -map problem in convert/mogrify utilities. * Fixed -remote problem with display utility (returns correct error status). 2002-10-16 Cristy * -border with a single value now produces correct results (e.g. -border 10). * Added -lat to convert/mogrify (local adaptive thresholding). 2002-10-15 Cristy * Set locale type LC_NUMERIC to "C". * Bug fix for PS2 encoder. * Added PS-Adobe preamble to PS3 encoder. 2002-10-14 Cristy * ImageMagick 5.5.1 released. 2002-10-12 Bob Friesenhahn * Use ImageMagick release number to allow multiple ImageMagick releases to co-exist without interference on the same machine. 2002-10-09 Bob Friesenhahn * Decided that DrawGet functions should return by value. 2002-10-06 Glenn Randers-Pehrson * Added detailed logging to BMP, PNG, and JPEG codecs, including JPEG quality estimate. 2002-10-01 Bob Friesenhahn * Added draw.h "DrawGet" equivalents to most of the "DrawSet" functions. * Added an array size argument to DrawSetDashPattern and got rid of the zero-termination garbage. * Remove `Set` from the names of draw.h functions which update the current affine transformation array (e.g. DrawSetRotate becomes DrawRotate). 2002-09-29 Bob Friesenhahn * Updated to Automake 1.7. 2002-09-29 Bob Friesenhahn * Under Windows, a DllMain function which automatically initializes ImageMagick (when ImageMagick is built using DLLs) may be added by defining ProvideDllMain in magick_config.h 2002-09-28 Cristy * Added resource consumption methods, see magick/resource.c. 2002-09-27 Cristy * Replaced underscores in commandline options with hyphens. For backward compatibility, underscores will continue to be recognized. * Added -blue-primary, -green-primary, -red-primary, -white-point options. 2002-09-27 Glenn Randers-Pehrson * Added BMP2 and BMP3 output formats. * Changed chromaticity primary.z from 1.0 to 1.0-(primary.x+primary.y) in the PNG and PCD codecs. 2002-09-21 Cristy * Added `exception` parameter to the ImageMagick progress monitor API. * Added enumerated types for the dispose member of the Image structure. * Added -version option to commandline utilities. 2002-09-21 Glenn Randers-Pehrson * The xcf decoder would sometimes create artifacts when reading RLE-encoded grayscale images, due to the green and blue samples not being defined. 2002-09-13 Bob Friesenhahn * Update to Autoconf 2.54. 2002-08-08 Cristy * Added logging capabilities to the CORE API. This facility is useful for debugging. Added "events" parameter to the -debug commandline option. * AcquireImagePixels() did not always return the same pixel values for virtual pixels when the cache was stored on disk (very rare). * new -virtual-pixel command line option. * new PerlMagick virtual-pixel image attribute. 2002-08-07 Cristy * ImageMagick 5.4.9 released. 2002-09-06 Leonard Rosenthol * Fixed some bugs in the Clipboard coder * Added new ImageToHBITMAP function to NTFeature.c/.h in core * Added support for Quantum==32 to IMDisplay 2002-08-30 Bob Friesenhahn * Fix formatting in the *.mgk files so that they are XML conformant 2002-08-30 Glenn Randers-Pehrson * QuantizeImage() did not always produce proper bilevel images. 2002-08-23 Bob Friesenhahn * Apply prefix/suffix transformations to ImageMagick program names which are substituted into delegates.mgk. This fix was requested by Glenn Randers-Pehrson. 2002-08-25 Cristy * Arcs are now rendered properly. * Use -authenticate to specifiy a password when viewing encrypted PDF's. * -page was previouly being ignored. * Configure files are returned as blobs now (suggested by William Radcliffe). 2002-08-23 Bob Friesenhahn * Added --disable-installed option to configure to support building an ImageMagick which is not installed via hard-coded paths. This is intended to be used for the ad-hoc binary distributions built by ImageMagick Studio. * The UseInstalledImageMagick define is to be used by builds formally installed under a prefix, or via the Windows registry. * Replaced GetMagickConfigurePath() with the three functions FindConfigurationFile(), FindFontFile(), and FindModuleFile(). * Re-implemented InitializeMagick() to try harder at finding the uninstalled ImageMagick without the help of MAGICK_HOME. In the future, it can try even harder. * Unix binaries packages (built with --disable-installed) should now work using the same file layout as the distribution file. There is no longer a need to put all files in the same directory. 2002-08-22 Bob Friesenhahn * Under Windows, define UseInstalledImageMagick to locate components using the registry rather than scanning the filesystem. 2002-08-19 Bob Friesenhahn * Added DrawSetTextEncoding() function to specify text encoding (e.g. "UTF-8"). 2002-08-16 Bob Friesenhahn * Extend `convert -list type` output so it prints more details. * Fix draw.c problem when specifying font family names that contain spaces. 2002-08-15 Cristy * Finished 32-Bit QuantumDepth support. * Subimage memory leak fixed (bug report by William Radcliffe). * Fixed subimage specification memory overrun. * Subimage specification did not work properly under Windows. 2002-08-15 Bob Friesenhahn * Fix problem with TEXT encoder. It was prepending the filename to the text. 2002-08-15 Bob Friesenhahn * Render Postscript via Ghostscript DLL (gsdll32.dll) under Windows if it can be loaded. Only ps.c currently uses this to verify there are no problems. 2002-08-14 Cristy * Added 16-bit raw write support to PPM. 2002-08-13 Bob Friesenhahn * Re-implemented ReadTTFImage() using the draw.h APIs. 2002-08-09 Bob Friesenhahn * Fixed a libtool bug in order to allow passing -m64 to allow building 64-bit ImageMagick using gcc 3.1 or later under SPARC Solaris. 2002-08-04 Cristy * Added experimental 32-bit QuantumDepth pixel support. * Stream support was not thread-safe (bug report by William Radcliffe). * Push/PopImagePixels() now recognizes the proper buffer length (previously it operated on one scanline at a time). * Deprecated Down/Upscale defines. Replaced them with Scale*ToQuantum() and ScaleQuantumTo*() methods. 2002-08-02 Bob Friesenhahn * Changed configure argument --disable-16bit-pixel to --with-quantum-depth in order to make its usage more straightforward and generic. Build ImageMagick using an eight-bit quantum via --with-quantum-depth=8. * Magick++ library builds as a DLL under Windows now. 2002-07-31 Cristy * Delegates/modules are restricted to hard-coded search paths (a security feature suggested by Bob Friesenhahn). 2002-07-29 Bob Friesenhahn * Added SubstituteString to utility.c for performing substitions on strings. * Added support for performing Ghostscript-related substitutions while reading delegates.mgk and type.mgk files. 2002-07-27 Bob Friesenhahn * Added the Windows utility functions NTGhostscriptDLL(), NTGhostscriptEXE(), and NTGhostscriptFonts(), to find the DLL, executable, and font directory corresponding to the newest Ghostscript install on the system. 2002-07-25 Bob Friesenhahn * Split nt.c into ntbase.c and ntfeature.c * Split nt.h into ntbase.h and ntfeature.h * Invoke NTIsMagickConflict() under Cygwin to ensure that drive letters in file specifications are not confused with magick strings. * Invoke NTGetTypeList() under Cygwin to read the list of Windows fonts. 2002-07-21 Bob Friesenhahn * Created Windows "setup.exe" style installation package for ImageMagick. * Include PerlMagick Perl extension for ActiveState ActivePerl as checkmark install option in Windows installation package. * Include ImageMagickObject OLE Object for WSH and Visual Basic (not IIS!!!) as checkmark install option in Windows installation package. * Windows installation package establishes file extension associations for ImageMagick. 2002-07-17 Glenn Randers-Pehrson * PPM files were being written in P4 or P5 format if all pixels were gray. This is correct behavior for the PNM format but not for the PPM format. 2002-07-13 Bob Friesenhahn * Load font information from Windows rather than depending on hand edited type-windows.mgk file. Still not incorporated in Cygwin build. 2002-07-04 Cristy * Typos corrected in perl.html (thanks to Ron Savage); * A color profile is now correctly referred to as ICM instead of IPTC. * Added XPM color compliance to colors.mgk. * $image->Get(`clip-mask`) now returns the clipping image. 2002-07-03 Bob Friesenhahn * Added NTRegistryKeyLookup() to nt.c in order to look up ImageMagick installation parameters from the Windows Registry. * Updated GetMagickConfigurePath() in magick.c to use installation path data from the Windows Registry (if available). * Updated VisualMagick/ImageMagick.iss so that Windows Registry is updated by install package. 2002-07-03 Cristy * Semaphore.c will compile now when pthreads are not present. * 8-Bit Quantum PCD images now read correctly. * The antialias member of the ImageInfo structure was not being cloned. 2002-07-01 Cristy * ImageMagick 5.4.7 released. 2002-06-30 Bob Friesenhahn * magick/nt.c (readdir): Make readdir re-entrant for each instance of DIR. This should improve thread safety. * ltdl/ltdl.c : Support building as DLL under Win32. 2002-06-20 Bob Friesenhahn * Update to use Automake 1.6.2 2002-06-20 Bob Friesenhahn * Try harder when searching for Ghostscript fonts under Linux. 2002-06-19 Bob Friesenhahn * Identify PICT files via magic.mgk. 2002-06-18 Cristy * Added PerlMagick threading support (patch by Doug MacEachern). 2002-06-16 Bob Friesenhahn * CLIPBOARD and EMF modules compile under MinGW and Cygwin. 2002-06-14 Glenn Randers-Pehrson * The wbmp writer would dump core if it received a DirectClass image that contained only black and white pixels, because no colormap exists. 2002-06-09 Cristy * Label color could not be set (bug report by Ron Savage). * Added CatchException() method to magick/error.c. 2002-06-06 Cristy * ImageMagick, version 5.4.6-1 released. 2002-06-05 Cristy * Added -encoding option to command line utilities. 2002-06-02 Cristy * ImageMagick, version 5.4.6 released. 2002-05-29 Bob Friesenhahn * ImageMagick may now be built (static build only) using the free MinGW development package from http://www.mingw.org. Leonard's "clipboard" coder is included in the build. 2002-05-28 Leonard Rosenthol * Added new "clipboard" coder for reading/writing the system's clipboard. Currently this is only implemented on Windows. For example: `convert logo: clipboard:`, `convert clipboard: foo.png`. 2002-05-28 Bob Friesenhahn * Support autotrace via delegates.mgk. For example: `convert autotrace:file.png file.mvg`. 2002-05-25 Bob Friesenhahn * Added progress monitor support to DrawImage(). 2002-05-25 Bob Friesenhahn * Added progress monitor support to wmf.c. 2002-05-11 Bob Friesenhahn * Added EscapeText() to utility.c to support escaping text. 2002-05-11 Bob Friesenhahn * Text escaping for -draw and DrawAnnotation was not working properly. Now it does. Backslash should act as a escape for the the active quote character (', ", or }) as well as backslash. The backslash should be discarded if it was used as an escape character. In order to reliably pass a backslash, two successive backslashes are required (e.g. "\\"). 2002-05-11 Bob Friesenhahn * Modified Base64Encode() of utility.c so that it returns the number of characters encoded. This avoids having to invoke strlen() on possibly megabytes of data. 2002-05-11 Bob Friesenhahn * Fixed compilation error with Sun Workshop compiler (wmf.c). 2002-05-11 Bob Friesenhahn * Implement polypolygon support in WMF renderer. Requires libwmf 0.2.4 with draw_polypolygon IPA callback. 2002-05-10 Bob Friesenhahn * Added --enable-ccmalloc configure option. 2002-05-09 Cristy * DCM patch provided by Shane Blackett. 2002-05-07 Cristy * Lock mutex when destroying a SemaphoreInfo structure (patch provided by William Radcliffe). * Added mingw patches provided by Derry Bryson. 2002-05-05 Cristy * ImageMagick, version 5.4.5-1 released. 2002-04-30 Cristy * Subimage specification did not work for TIFF (e.g. convert `image.tiff[1]` image.png). 2002-04-30 Cristy * ImageMagick, version 5.4.5 released. 2002-04-20 Cristy * Added magic string detection for the FPX format (patch provided by Marc). 2002-04-18 Cristy * Added ExceptionInfo parameter to C API method, QueryColorDatabase(). 2002-04-17 Leonard Rosenthol * Fixed all known bugs with the IMDisplay utility for Windows. 2002-04-17 Bob Friesenhahn * configure.ac (libtool_build_static_libs): Added --enable-delegate-build option to suuport building ImageMagick using delegate libraries in subdirectories of the ImageMagick source directory. 2002-04-16 Bob Friesenhahn * WMF now supplies bitmaps as inline images rather than via a mpri reference. 2002-04-15 Cristy * Fixed DrawImage() to properly handle affine image transforms. * Added AffineTransformImage() to C API. * Added -transform option to convert/mogrify program. 2002-04-13 Bob Friesenhahn * magick/magick.c (MagickToMime): New method to return the MIME media type corresponding to a specified magick tag. 2002-04-12 Leonard Rosenthol * Fixed a bug in writing layer names in PSD files. 2002-04-10 Cristy * Fixed PingImage() memory leak (thanks to Timo Vogel). * Added encoding and unicode attributes to PerlMagick (patch provided by Youki Kadobayashi). 2002-04-08 Cristy * Added reference counted blobs. * Added MagickFatalError() and SetFatalErrorHandler() to the C API. * One color images caused memory corruption in QuantizeImage() (thanks to Vincent Broz). * Memory leak in NormalizeImage() (thanks to Vincent Broz). 2002-04-06 Glenn Randers-Pehrson * Added CCIS-601 4:2:2 YUV format read-write support. * Added CCIS-601 4:2:2 MPEG-2 format write support. * Fixed a bug introduced in 5.4.0 that caused files with "M2V" suffix to be written in MPEG-1 instead of MPEG-2 format. 2002-03-28 Cristy * ImageToBlob() only returned the first frame of a multi-frame image. 2002-04-05 Leonard Rosenthol * Fixed inversion of colors when converting CMYk JPEG to PDF 2002-04-01 Bob Friesenhahn * Fixed TTF preview function. 2002-03-28 Cristy * DCM patches provided by Syam Gadde. * Multi-frame MPC image files caused a fault under Windows. * Copy entire comment from SVG (bug report from Bob Friesenhahn). * Enlarged scanline buffer for JPEG-compressed TIFF's (bug report from Bob Friesenhahn). 2002-03-27 Cristy * ImageMagick, version 5.4.4, released. 2002-03-26 Bob Friesenhahn * Added preliminary version of C API for vector drawing commands (draw.h & draw.c). This interface is subject to change, and has not even been tested yet so it should not be used to support production code. The previous draw.h and draw.c have been renamed to render.h and render.c respectively. 2002-03-25 Leonard Rosenthol * Fixed bugs related to layered CMYK PSD images. 2002-03-13 Leonard Rosenthol * PSD coder now saves layer information (name, offset & opacity) in hidden attributes. 2002-03-13 Cristy * Enhanced MPC to read/write image sequences. 2002-03-13 Cristy * A number of formats (e.g. JPEG, PS) did not handle DirectClass grayscale images properly. 2002-03-12 Cristy * Changed Clone*Info() API so structure members are set directly rather than by the *clone=*info method (suggested by William Radcliffe). 2002-03-11 Cristy * Added AcquireString() to allocate read-only strings. 2002-03-10 Bob Friesenhahn * coders/null.c (WriteNULLImage): Support writing "null:" image type for use when profiling or testing ImageMagick. 2002-03-08 Bob Friesenhahn * Update to Autoconf 2.53 (new release) * Update to Automake 1.6 (new release) 2002-03-07 Cristy * Bob Friesenhahn's execution profile results in a number of speed-ups with a faster LocaleCompare() algorithm and self-adjusting lists. * Recognize additional DCM metadata (suggested by Barry Branham). * Fixed CopyOpacity composite operator for CMYKA images. 2002-03-06 Cristy * Inlined AlphaComposite() and ValidateColormapIndex(). * Corrected compositing algorithm for the case where both source and destination pixels had opacity values that were neither fully transparent nor fully opaque. 2002-03-05 Cristy * Memory overrun when drawing large circles. 2002-03-04 Cristy * Removed bug introduced into Bob's Base64Encode() method. 2002-03-02 Bob Friesenhahn * Added Base64Decode() and Base64Encode() to utility.c and updated ReadInlineImage() in magick/constitute.c to use Base64Decode(). 2002-03-01 Cristy * GetTypeInfoByFamily() null pointer fault (reported by Bob Friesenhahn). * Added module version number (patch by Glenn Randers-Pehrson). 2002-03-01 Glenn Randers-Pehrson * image->matte was not being set when reading GRAY-ALPHA PNG files. 2002-02-26 Cristy * Potential infinite loop in SyncBlob() (reported by Vladimir Faiden). 2002-02-26 Cristy * Gravity not respected when drawing text with the convert program. 2002-02-21 Cristy * MPEG multi-part filenames require an embedded %d, not %lu. * WriteStream() did not write to fifo (thanks to William Radcliffe). 2002-02-20 Cristy * Annotation did not support SJIS properly (patch provided by Katsutoshi Shibuya). 2002-02-18 Cristy * Fixed memory overrun with -format option of the mogrify program. * Labels were not positioned correctly for VID format. 2002-02-16 Cristy * Replaced -copy/-replace options with +/-write in the convert program. * Median filtering speed enhancement using skip list contributed by Mike Edmonds. 2002-02-14 Cristy * Command line options now stay in effect for any image in command line order until a another option is encountered or if -noop is specified. 2002-02-07 Cristy * SVG coders understands inline images. 2002-02-06 Cristy , Glenn Randers-Pehrson * Made -scene consistent across all utilities. -snaps replaces previous functionality of -scene for import program. 2002-01-30 Cristy * Correctly draw arc when arc end/start are not integer (patch contributed by Giuliano Pochini). 2002-01-28 Cristy , Glenn Randers-Pehrson * Geometry strings respect -gravity (e.g. -gravity SouthWest -crop 100x100). * Postive offsets in geometry strings move within the image canvas with respect to the gravity (SouthWest gravity is similar to Postscript page offsets). 2002-01-24 Cristy * Use -trim to trim the edges of an image. * Palm pixmap supported contributed by Christopher R. Hawks. * Added -mask to the convert/mogrify programs to add clips masks to an image. 2002-01-21 Cristy * Fixed occasional small memory leak associated with exceptions. * Persistent cache is no longer updated (MPC coder). 2002-01-20 Glenn Randers-Pehrson * Fixed some bugs in the uncompressed PGM and PPM reader/writer (pnm.c). 2002-01-14 Bob Friesenhahn * configure.ac: Removed test for libwmf/font.h. 2002-01-13 Leonard Rosenthol * More bug fixes and improvements in PSD writer. 2002-01-13 Bob Friesenhahn * magick/magic.mgk: Added entries for detecting PFA and PFB formats. Is this file used for anything anymore? * coders/modules.mgk: Add support for PFA fonts. * coders/ttf.c (RegisterTTFImage): Add support for PFA fonts. * magick/annotate.c (RenderType): Add support for PFA fonts. 2002-01-12 Bob Friesenhahn * Modified type.mgk so that it may include the additional files type-windows.mgk, type-solaris.mgk, and type-ghostscript.mgk depending on the operating system used, and the font files available. 2002-01-11 Leonard Rosenthol * PSD now supports writing layered images and IPTC data * Fixed some bugs in XCF 2002-01-11 Cristy * Added image list methods to the API. 2002-01-10 Bob Friesenhahn * configure.ac : Renamed configure option --with-ttf-fontpath to --with-fontpath since ImageMagick loads more than TrueType fonts. * ChangeLog : Renamed Changelog.txt to ChangeLog in order to conform to GNU and open-source standards. 2002-01-06 Bob Friesenhahn * Makefile.am : $(DESTDIR) already contains trailing `/`. 2002-01-06 Bob Friesenhahn * coders/wmf.c (wmf_magick_device_begin): Fix non-opaque fills. Now properly fills with texture image. 2002-01-05 Glenn Randers-Pehrson * Fixed an out-of-bounds memset() and two other memory overruns when decoding 1-bit AVI, BMP, and DIB images. 2002-01-04 Bob Friesenhahn * Fix lcms header inclusion in transform.c. 2002-01-03 Bob Friesenhahn * coders/wmf.c (magick_brush): Fixed bug with setting fill color. 2002-01-03 Cristy * Postscript Level II is now DCS compliant. ================================================ FILE: pkg/gocv/cgo/third_path/graphics-magick/share/doc/GraphicsMagick/ChangeLog.2003 ================================================ 2003-12-28 Bob Friesenhahn * magick/annotate.c (RenderFreetype): Ensure that image storage class is set to DirectClass. Text rendering was not working properly on top of PseudoClass images. * magick/map.c (MagickMapRemoveEntry): Logic didn't properly handle removing entry in list. * configure.ac: Added --enable-efence option to enable memory debugging using Electric Fence. 2003-12-27 Bob Friesenhahn * tests/maptest.c (main): Extended test to add an entry to the list after an entry has already been removed. * magick/image.c (ColorspaceTypeToString): Add support for LAB colorspace. * magick/map.c: Added signature members to all structures and added assertions to ensure that the signature == MagickSignature prior to use. MagickMapAllocateObject now initializes the object reference count to one, and MagickMapDestroyObject decrements it in order to be more correct even though the object reference count is not actually used yet. (MagickMapCopyString): Preserve a null argument, and use AcquireString since it doesn't enlarge the string storage. (MagickMapCopyBlob): Preserve null blobs. * configure.ac: Search for the shmctl() function. Under current Cygwin, this is hiding in -lcygipc. 2003-12-26 Bob Friesenhahn * magick/composite.c: Fixed the composite operator list in the CompositeImage documentation. * www/api/types.html: Corrected list of composition operators. Sometime prior to the creation of GraphicsMagick, the "Replace" composite operators were renamed to be "Copy" composite operators. Thanks to David Relson for bringing this problem to our attention. * PerlMagick/Magick.xs: Added "LAB" to colorspace types. * magick/image.h (enum ColorSpace): Add LABColorspace enumeration. * wand/magick_wand.h : Add some compatibility definitions to translate from ImageMagick enumerations to existing GraphicsMagick enumerations. 2003-12-25 Bob Friesenhahn * magick/annotate.c: Use header synonyms defined by FreeType's ftheader.h (included via ) to include FreeType headers. This will presumably be more portable in the future. * configure.ac: is an optional prerequisite for and so include it when testing for these headers. * magick/annotate.c: Include if it is available. 2003-12-21 Bob Friesenhahn * wand/wandtest.c: Ported from latest ImageMagick version. * wand/drawing_wand.c: Adapted to be compatible with latest ImageMagick version. * wand/pixel_wand.c: Adapted to be compatible with latest ImageMagick version. * wand/magick_wand.c: Ported from latest ImageMagick version. * magick/image.h (Image): Members color_profile, iptc_profile, generic_profile, and generic_profiles are now deprecated and private although they continue to work as before. Please migrate existing code to use the GetImageProfile and SetImageProfile functions since these members will eventually be removed. * magick/image.c (GetImageProfile): New function to retrieve an image profile. Return value differs from similarly named ImageMagick method since the ImageMagick approach assumes a particular storage method. (SetImageProfile): New function to add (or remove) an image profile. Does not execute CMS color profiles. * magick/cache.c (SetImageVirtualPixelMethod): Return unsigned int to make the Wand implementation happy. * magick/image.c (TransformColorspace): Return unsigned int to make the Wand implementation happy. (SetImageType): Return unsigned int to make the Wand implementation happy. * magick/draw.h, magick/draw.c: Substitute `unsigned long` in place of `size_t` in interfaces so that the draw API is not sensitive to the definition of _LP64. * locale/C.mgk: Added new messages required by Wand library. * magick/error.c (ExceptionSeverityToTag): Add tag translations for the WandWarning, WandError, & WandFatalError enumerations * magick/error.h (enum ExceptionType): Add WandWarning, WandError, & WandFatalError enumerations to ExceptionType for ImageMagick API compatibility. * magick/image.h (enum ChannelType): Add an `AllChannels` enumeration to the ChannelType enumeration for ImageMagick API compatibility. 2003-12-17 Bob Friesenhahn * PerlMagick, tests: Adjusted allowed error values for tests based on new error computation arithmatic. Some tests were left failing since the operation they test provides results which are unreasonably inaccurate, or obviously broken. 2003-12-17 Glenn Randers-Pehrson * coders/jpeg.c: Changed "JPEG:preserve-settings from a key/value pair to a simple flag. Save and restore attributes when "-define JPEG:preserve-settings" appears on the commandline. Use "+define JPEG:preserve-settings" to unset the flag. 2003-12-16 Bob Friesenhahn * coders/wmf.c: Include if it is available since some libwmf installs don't work unless it is included before the libwmf API headers. * configure.ac: Check for . 2003-12-16 Glenn Randers-Pehrson * coders/jpeg.c: Changed stored jpeg quality attribute from [jpeg-quality] to JPEG-Quality. Added attributes JPEG-Colorspace and JPEG-Sampling-factors. Added code to save and restore these attributes when "-define JPEG:preserve-settings=yes" is present in the comandline. Quality is restored if the input was a JPEG and the quality was preserved. Sampling factors are restored if the input was a JPEG, sampling factors were preserved, and the colorspace for the output file is the same as that of the input file. 2003-12-15 Bob Friesenhahn * TclMagick/source/configure.ac: Add an initial TclMagick configure-based build environment based on a template and macros from the Tcl project. I recall that while the extension does build, it is possible that it is not properly registered as a module to Tcl. 2003-12-14 Bob Friesenhahn * magick/image.c (IsImagesEqual): Properly compute error distance vectors. Math was missing the necessary sqrt call. Also, pre-normalize the error differences to 1.0 in order to reduce the storage size required to store the summation of error values. * PerlMagick/t/composite.t: Update Minus and Xor reference images. * magick/composite.c (CompositeImage): Incorporated fixes from ImageMagick for XorCompositeOp, PlusCompositeOp, and MinusCompositeOp. Thanks to John Cristy for bringing the need for these fixes to our attention. * magick/image.h (RoundToQuantum): Added missing parenthesis. 2003-12-10 Bob Friesenhahn * doc/environment.imdoc: Document MAGICK_CODER_MODULE_PATH and MAGICK_FILTER_MODULE_PATH. * rungm.sh.in: Pass MAGICK_CODER_MODULE_PATH and MAGICK_FILTER_MODULE_PATH in the environment so modules build may be tested without first being installed. * magick/module.c (FindMagickModule): Use the MAGICK_CODER_MODULE_PATH environment variable to specify a search path for coder modules. Use MAGICK_FILTER_MODULE_PATH to specify a search path for filter modules. * Makefile.am: Updated to Automake 1.8. (install-exec-perl): Fixes which achieve a successful `make distcheck` for the first time in *Magick history. * configure.ac: Set scripts to executable. 2003-12-09 Bob Friesenhahn * Makefile.am (uninstall-data-html): Pathnames were computed incorrectly so documentation directories were being left behind. * configure.ac: --without-frozenpaths is now the default. This helps `make distcheck` work and makes the package more portable. Path to gm was being incorrectly frozen when --without-frozenpaths was specified. * magick/delegate.c (ReadConfigureFile): Validate delegate paths prior to substitution. * rungm.sh.in (top_builddir): Use a more reliable scheme for computing location of source and build directories. * magick/Makefile.am: Improve include directory computation logic. * configure.ac: Don't override includedir. Pass user-supplied LIBS to the linker. 2003-12-08 Glenn Randers-Pehrson * coders/jpeg.c: store JPEG quality as "[jpeg_quality]" attribute. 2003-12-07 Bob Friesenhahn * rungm.sh.in: New script to support executing uninstalled executables. * magick/blob.c (GetConfigureBlob): New MAGICK_CONFIGURE_PATH environment variable allows the user to specify the search path for configuration (.mgk) files. 2003-12-06 Bob Friesenhahn * index.html: Added a table showing current stable release and development version. 2003-12-05 Bob Friesenhahn * doc/options.imdoc (use): Describe the syntax of the -process argument. * acinclude.m4 (AC_CHECK_CC_OPT): Add quoting in AC_CHECK_CC_OPT definition. Change suggested by Patrick Welche 2003-12-04 Bob Friesenhahn * magick/magick.c (GetMagickInfo): Fix preprocessing logic error which caused moby shared library build to not register static modules. 2003-12-03 Bob Friesenhahn * magick/module.c (ExecuteModuleProcess): Add some logging. * magick/static.c (ExecuteStaticModuleProcess): Add some logging. 2003-11-30 Bob Friesenhahn * VisualMagick/installer: Add optional build support for LZW. * wand/Makefile.am: Add AUTOMAKE_OPTIONS. * configure.ac: Update to Autoconf 2.59. 2003-11-29 Bob Friesenhahn * VisualMagick/installer/inc/tasks-install-perlmagick.isx: Update to reflect that the next release will use ActivePerl 5.8.1 Build 807. * VisualMagick/installer/inc/files-configs.isx: Updated the source locations for the .mgk files. Install modules.mgk into the config directory rather than the modules directory. * configure.ac: Fixes to work with latest CVS libtool. * libtool.m4: Update to latest CVS libtool. * magick/modules.c, magick/static.c (ExecuteStaticModuleProcess): Fix conditional compilation logic so that "moby" shared library build works again. * magick/compress.c, magick/mac.c: Use existing SaveImageText and LoadImageText global constants rather than separate defines. 2003-11-17 Bob Friesenhahn * configure.ac: Update to Autoconf 2.58. * Makefile.am: Update to Automake 1.7.9. 2003-11-14 Bob Friesenhahn * magick/draw.c (DrawComposite): Base64-encoded image was not being deallocated. Bad memory leak. 2003-11-03 Mike Chiarappa * BCBMagick: Updated installation procedure. Please read BCBMagick/readme.txt for details. 2003-11-03 Mike Chiarappa * BCBMagick: Released DLL Version. Please read BCBMagick/readme.txt for details about installation and/or use. 2003-11-03 Lars Ruben Skyum * magick/utility.c (GetPathComponent): Added x, X, and + characters to list of legal characters in subimage specifications. Required by raw RGB image reader which accepts the syntax "image.rgb[100x100+50+50]". Thanks to John Cristy for catching that one. 2003-11-02 Bob Friesenhahn * magick/locale.c (GetLocaleMessageFromID): Fix ID range checking logic. 2003-10-30 Lars Ruben Skyum * coders/jpeg.c: changed to not write gray CMYK images as grayscales. That would not be a valid optimization. * magick/color.c (IsGrayImage, IsMonochromeImage): Changed to never return true for CMYK images. Separated images get wrong colors when optimized to grayscales based on what these two functions return. Gray and CMYK are two different color spaces. * magick/nt_feature.c (NTIsMagickConflict): changed to accept colon as part of the magick string, consistent with the way the function is used. * magick/utility.c, magick/utility.h (ExpandFilenames, GetPathComponent): Fixed filename glob expansion. Added handling of filename prefix-magick and sub-image specification to GetPathComponent. Sub-image specification takes precedence over any filename patterns. 2003-10-22 Bob Friesenhahn * magick/static.c (ExecuteModuleProcess): Renamed from ExecuteStaticModuleProcess. Only compiled if SupportMagickModules is not defined. * magick/type.c (GetTypeBlob): Eliminated function. (ReadTypeConfigureFile): Use GetConfigureBlob() rather than GetTypeBlob(). * magick/module.c (GetModuleBlob): Eliminate this function since modules.mgk is now installed under ${prefix}/share/GraphicsMagick-version/config so GetConfigureBlob() may be used. (lt_dlexit, etc.) Eliminate fake libltdl function wrappers used for the static build. (DestroyMagickModules): Added a new destroy function (simply invokes DestroyModuleInfo()). (GetModuleList): Learn where modules live by using FindMagickModule() to locate the LOGO module rather than by using the location of modules.mgk. This is necessary since now modules.mgk may be seperate from the modules. (GetModuleBlob): Eliminated function. (InitializeMagickModules): New function to safely initialize the module loader. (OpenModule): Added logging messages. (OpenModules): Added logging messages. (ReadModuleConfigureFile): Use GetConfigureBlob() rather than GetModuleBlob(). Totally eliminated the rat's-nest of conditional code dependent on SupportMagickModules. Now all the code in module.c is dependent on #if defined(SupportMagickModules). * magick/magick.c (DestroyMagick): Invoke DestroyMagickModules(). (GetMagickInfo): #ifdef chunks of code which exist to support the modules-build rather than forcing the module loader to pretend that modules are being used when they are not. Pass module loading exceptions back to the user rather than discarding them. (GetMagickInfoArray): Don't inspect the exception status since may short-circuits the operation. Use best-effort instead. (ListMagickInfo): Don't inspect the current exception status so that all the modules which did load successfully will be represented. (InitializeMagick): Invoke InitializeMagickModules(). * magick/log.c: (GetLogBlob): Eliminated function. GetConfigureBlob() is safe to use now when configuring logging. (LogToBlob): Simplified function. Only exists since FileToBlob() may throw exceptions (which are logged, causing deadlock). (ReadLogConfigureFile): Use GetConfigureBlob(). * magick/blob.c (GetConfigureBlob): Re-written to use the MagickMap interface and to support the new `lib` and `share` config directories. The directory ${prefix}/lib/GraphicsMagick-version/config is scanned before ${prefix}/share/GraphicsMagick-version/config. (FileToBlob): Simplified implementation. * config/Makefile.am: New makefile to install .mgk files. * magick/magick_config.h.in: Added MagickLibConfigPath and MagickShareConfigPath defines. * configure.ac: Install configuration files (.mgk files) in ${prefix}/lib/GraphicsMagick-version/config and ${prefix}/share/GraphicsMagick-version/config. Architecture independent files to under "share" while architecture dependnet files go under "lib". * Makefile.am: Added `config` subdirectory to distribution. All .mgk files are moved from `coders` & `magick` into this single directory. 2003-10-21 Mike Chiarappa * magick/studio.h: small modifications to achieve DLL compilation of library with Borland C++ Builder. * coders/ps3.c (ZLIBEncode2Image): Fixed bug. Compilation fail when HasZLIB is undefined because parameters 5 and 6, are undefined. 2003-10-16 Bob Friesenhahn * libtool.m4: Updated libtool again to CVS latest version. Libtool required some fixes for building DLLs under MinGW. * magick/resource.c (InitializeMagickResources): Some code is conditional based on HAVE_POPEN. * magick/utility.c (SystemCommand): Improved conditional compilation logic. * magick/blob.c (OpenBlob): Code depending on popen() is conditionally compiled based on HAVE_POPEN. Code depending on pclose() is conditionally compiled based on HAVE_PCLOSE. * configure.ac: Add test for _pclose(), pclose(), _popen(), and popen(). * magick/locale.c (GetLocaleMessage): Add missing MagickExport. (GetLocaleMessageFromID): Add missing MagickExport. * VisualMagick/installer/inc/files-development.isx (Source): Include all of the headers from the magick directory in the development package. Including them individually is too error prone. 2003-10-15 Bob Friesenhahn * VisualMagick/magick/magick_config.h.in: Added PREFIX_MAGICK_SYMBOLS as a configuration option. * magick/module.c (_CoderInfo): Added register_function and unregister_function members to record the module's register and unregister function addresses. (OpenModule): Locate the module's register and unregister functions and save their address to the module's CoderInfo record. (UnloadModule): Invoke the module unregister function using the address recorded by OpenModule(). (TagToFunctionName): If PREFIX_MAGICK_SYMBOLS is defined, then add a "Gm" prefix to the register and unregister function names. * libtool: Updated libtool files to the latest CVS version. * configure.ac: Changed define name from MAGICK_SYMBOL_PREFIX to PREFIX_MAGICK_SYMBOLS since support is not available for specifying an arbitrary prefix. 2003-10-14 Bob Friesenhahn * configure.ac: Added --enable-symbol-prefix configure option which prepends "Gm" to all GraphicsMagick library symbols using the C pre-processor. In the future, this may change to support specifying an arbitrary prefix, depending on experience. * magick/studio.h: Include magick/symbols.h. * magick/api.h: Include magick/symbols.h. * magick/symbols.h: New header to support optionally remapping library symbols. If MAGICK_SYMBOL_PREFIX is defined, then library symbols are remapped. 2003-10-13 Bob Friesenhahn * magick/api.h: Removed inclusion of since it is an implementation header. 2003-10-13 Lars Skyum * www/GraphicsMagick.html, www/animate.html, www/composite.html, www/conjure.html, www/convert.html, www/display.html, www/gm.html, www/identify.html, www/import.html, www/mogrify.html, www/montage.html: added documentation for "-define" command line option. * doc/brief_options.imdoc, doc/options.imdoc: Added documentation for "-define" command line option. * doc/gmdocselect, doc/imdocselect: Changed "skipform" label in sed scripts to just "skipf". Solaris sed had problems with the long(?) "skipform" label. 2003-10-12 Bob Friesenhahn * doc/composite.imdoc, doc/options.imdoc, doc/GraphicsMagick.imdoc: Attempted to clarify the meaning of the compose arguments and how composition works, as well as eliminating use of hard-coded values like 255. * www/links.html: Added a link to Michael Still's article "Graphics from the command line". 2003-10-11 Bob Friesenhahn * coders/*.c: Updated module descriptions so that they accurately describe the module rather than saying "Read/Write GraphicsMagick Image Format". * coders/cineon.c: Fix source module description. Contrary to opinion, ImageMagick did not invent the Cineon X image format so description is now "Read/Write Cineon X Image Format." * magick/magic.mgk: Added a CINEON entry for the Cineon X image format. * magick/static.c (RegisterStaticModules): Invoke RegisterCINEONImage(). * coders/modules.mgk: Map "CIN" magick to CINEON module. 2003-10-10 Bob Friesenhahn * locale/C.mgk: Added message for "UnrecognizedCommand". * magick/command.c (MagickCommand): No error was reported when a subcommand failed to be matched so `gm foo` would silently return. Now an error message is properly reported. 2003-10-09 Bob Friesenhahn * Makefile.am: Updated to Automake 1.7.8. * various: Edits to eliminate minor issues detected by SGI C compiler. * coders/ps3.c (WritePS3Image): Variable `value` was set but never used so it is removed. * magick/image.c (RGBTransformPacket): Removed inline request since this function is too big to inline. * magick/animate.c (XAnimateBackgroundImage): Fixed a GCC 3.X "type pinning" warning. * magick/display.c (XDisplayBackgroundImage): Fixed a GCC 3.X "type pinning" warning. * magick/render.c (GetPixelOpacity): Removed inline directive. No one in their right mind could ever imagine this function inlining successfully. * magick/cache.c (IsNexusInCore): Adjusted so function inlines as requested. * coders/tiff.c (ReadTIFFImage): Improved logging information. (WriteTIFFImage): Changed the way the bilevel/grayscale logic works. Now bilevel images are treated similar to any other grayscale image unless CCITT FAX3 or FAX4 compression is requested (which selects the MINISWHITE photometric). The default is now to write uncompressed bilevel images with MINISBLACK photometric. * PerlMagick/t/composite.t: Use some reasonable error values. * magick/image.c (GetImageDepth): Added special cases for colormapped images and monochrome images in order to improve performance. 2003-10-09 Glenn Randers-Pehrson * NEWS: added info about color scaling, sampling-factor, and changed a reference to "-coder-options" to "-define". 2003-10-09 Lars Ruben Skyum * VisualMagick/bin/modules.mgk: added EPS3 mapping to PS3 module. * coders/ps3.c, coders/tiff.c, magick/command.c, magick/image.c, magick/image.h, magick/utility.c: Changed -coder-options option to -define. Also renamed functions {Add,Remove,Access}CoderOption(s) to {Add,Remove,Access}Definition(s). Changed ps coder-specific option ps:image=imagemask to just ps:imagemask. 2003-10-08 Bob Friesenhahn * coders/cineon.c: Imported and adapted Cineon image format coder written by Kelly Bergougnoux with assistance from John Cristy. 2003-10-08 Glenn Randers-Pehrson * coders/jpeg.c: Extended -sampling-factor option to allow user to supply full set of sampling factors. If the full set is not supplied, omitted ones are 1x1 by default, similar to the behavior of "cjpeg -sample". * magick/command.c: Accept multiple pairs of sampling factors. 2003-10-07 Bob Friesenhahn * coders/tiff.c (WriteTIFFImage): Re-arranged logging for improved output. Cleaned up evaluation of SAMPLESPERPIXEL and BITSPERSAMPLE. Provided support for the TIFF coder options tiff:samples-per-pixel and tiff:bits-per-sample for power users. (ReadTIFFImage): Colormap generation for PHOTOMETRIC_MINISBLACK and PHOTOMETRIC_MINISWHITE was inaccurate. Seems to be accurate now. * PerlMagick/t/reference/read/input.miff: Updated due to Glenn's change to scale macros. * PerlMagick/t/tiff/input_gray_12bit.tiff: Replaced 12 bit image with a different one which is written by GraphicsMagick. * coders/ps3.c (WritePS3Image): Use AccessCoderOption(). * magick/image.c (AccessCoderOption): Added a function to use for accessing coder-specific options. 2003-10-08 Lars Ruben Skyum * magick/attribute.c (TraceSVGClippingPath): optimized for speed and precision in clipping mask generation by using lines to connect Bezier curve anchor points where applicable. 2003-10-07 Glenn Randers-Pehrson * Revised ScaleColor5to8 and ScaleColor6to8 macros again, to fill the low bits correctly. 2003-10-06 Bob Friesenhahn * PerlMagick/t/tiff/read.t: Added 16-color and 256 color colormapped tests with a matte channel. * PerlMagick/t/tiff/write.t: Added 16-color and 256 color colormapped tests with a matte channel. * coders/tiff.c (WriteTIFFImage): When using LZW compression, apply the horizontal differencing predictor to RGB truecolor and deep gray images since the TIFF spec says that LZW compression is usually improved by using horizontal differencing with continuous tone images. Re-implemented grayscale and colormapped scanline preparation to use the new bit-stream interface. This is a bit slower, but very flexible, and the implementation is very compact. Writing of a matte (transparency) channel is now believed to be correct for all depths. * magick/command.c (MogrifyImage): Only transform the colorspace if it has been set (i.e. is not UndefinedColorspace). 2003-10-06 Glenn Randers-Pehrson * coders/png.c (ReadOnePNGImage): PNG decoder would exit too early when reading image.png[0]. 2003-10-05 Bob Friesenhahn * PerlMagick/t/tiff/write.t: Added TIFF write tests for 4 bits-per-sample TIFF images, both with and without a transparency channel. * magick/image.c (DescribeImage): Added -verbose support for displaying individual channel depths. 2003-10-06 Lars Ruben Skyum * magick/image.c (SetImageInfo): cleaned up parsing of subimage specification (image.psd[0]). It would fail sometimes due to incorrect reuse of variables. It's a bit strange the code accepts more range syntax-variations than can be stored in ImageInfo. 2003-10-05 Bob Friesenhahn * magick/image.c (ChannelImage): The OpacityChannel, MatteChannel, and BlackChannel operations set the matte channel to opaque, so set image->matte to False for those operations. (RGBTransformImage): Add an assertion to prevent passing the colorspace argument `UndefinedColorspace`. (TransformRGBImage): Add an assertion to prevent passing an image with colorspace set to `UndefinedColorspace`. 2003-10-04 Bob Friesenhahn * magick/log.c (LogToBlob): Since MagickSeek(file,0,SEEK_END) is used to obtain the Blob size, MagickSeek(file,0,SEEK_SET) must be used to restore the seek position. Thanks to John Cristy for bringing this to our attention. 2003-10-03 Bob Friesenhahn * magick/bit_stream.h: Added a bit-stream writer function. * PerlMagick/t/reference/read/input_tim.miff: Reference image was defective. 2003-10-03 Lars Ruben Skyum * magick/image.c, magick/image.h: Updated AddCoderOptions to accept "flag" keys that have no values. They are placed in the coder options map with an empty, zero length string value. Option argument syntax is now: "key1[=[value1]],key2[=[value2]],..." 2003-10-03 Lars Ruben Skyum * magick/command.c: Updated +coder-options option to not clear the entire map of coder options, but accept a list of names to remove from the map. Use option argument "*" to clear the entire map of coder options. * magick/image.c, magick/image.h: Added function RemoveCoderOptions. Added cast of signed char to unsigned char and int in calls to isspace and isprint. * magick/utility.c: Added cast of signed char to unsigned char and int in calls to isspace and isprint. Added special handling of +coder-options option in ExpandFilenames function. 2003-10-01 Bob Friesenhahn * PerlMagick/t/reference/read/input_tim.miff: The TIM read results changed somewhat due to Glenn's ScaleColor5to8 fix. 2003-10-01 Glenn Randers-Pehrson * Revised ScaleColor5to8 and ScaleColor6to8 macros to fill in the low bytes. * coders/bmp.c (ReadBMPImage): scaling of 8-8-8-8-bit images was also slightly incorrect. 2003-09-30 Glenn Randers-Pehrson * coders/bmp.c (ReadBMPImage): scaling of 5-5-5-bit and 5-6-5-bit images was slightly incorrect. 2003-09-30 Bob Friesenhahn * coders/tiff.c (ReadTIFFImage): When using the generic bit-stream marshaller to read colormapped/gray images, the slight performance improvement from creating a special case for matte images did not justify almost doubling the amount of code. Therefore, the two loops are combined back into one. 2003-09-29 Bob Friesenhahn * coders/tiff.c (ReadTIFFImage): Fixed reading grayscale TIFFs that have a transparency channel. Now uses a generic bit-stream marshaller to allow reading any grayscale or colormapped TIFF with any bits per sample in the range of 1 to 16. * magick/bit_stream.h: Added a generic implementation for marshalling from a bit-stream into a quantum. Still needs re-writing for best performance. * PerlMagick/t/tiff/read.t: Added a test case for reading 8-bit grayscale TIFF with matte. Corrected grayscale 12-bit read signatures. Added 16 color PseudoClass read test. Added 4-bit grayscale read test. 2003-09-26 Bob Friesenhahn * coders/tiff.c (WriteTIFFImage): Add support for writing DirectClass grayscale images at 4 bits per sample, including those with an opacity channel. This allows writing smaller files (half the size) when the image has 16 (or less) levels of gray. Use "gm convert inimage.tiff -depth 4 outimage.tiff" to quickly create grayscale TIFF file with 16 (or less) levels of gray. 2003-09-25 Bob Friesenhahn * NEWS: Updated NEWS file with changes since last update. * index.html: Added a link to the www/AUTHORS.html file, as well as text stating that GraphicsMagick is originally derived from ImageMagick 5.5.2, with a link to the ImageMagick site. * Makefile.am: Add rules to generate www/AUTHORS.html. * www/AUTHORS.html: New HTML file based on the AUTHORS file in the source package. GraphicsMagick has many authors. 2003-09-25 William Radcliffe * magick/image.c: Updated DescribeImage to cleanup EXIF data display based on work by Cristy in ImageMagick. 2003-09-24 Bob Friesenhahn * coders/tiff.c (WriteTIFFImage): Add support for writing colormapped TIFF images with 1, 2, & 4 bits per colormap index. This allows writing smaller files. 2003-09-24 Lars Ruben Skyum * coders/ps3.c: Now creates a correct %%BoundingBox for images with resolution stored as pixels per centimeter. Renamed serialize functions. Added comment headers where they were missing. Reformatted code to be in alignment with GraphicsMagick standard formatting. * magick/map.c: Fixed semaphore double locking problem in MagickMapCloneMap. 2003-09-23 Mike Chiarappa * BCBMagick/readme.txt : Updated compilation instructions. * BCBMagick/magick/libMagick.bpr : Updated project, now include map.c. * BCBMagick/lcms/Projects/BCB6/lcms.bpr : Updated project, now include cmscam02.c and cmsvirt.c. Much thanks to Alex Dvoretsky for bringing this problem to my attention. 2003-09-23 Bob Friesenhahn * magick/image.h (Image): Moved private members to bottom of structure. (_ImageInfo): Moved private members to bottom of structure. * magick/Makefile.am (pkginclude_HEADERS): Don't install semaphore.h. (noinst_HEADERS): Distribute map.h and semaphore.h. * magick/image.h (ImageInfo): Change coder_options member from type `MagickMap` to type `void *`. * coders/png.c: include magick/semaphore.h. * magick/blob.c: include magick/semaphore.h. * magick/color.c: include magick/semaphore.h. * magick/constitute.c: include magick/semaphore.h. * magick/delegate.c: include magick/semaphore.h. * magick/log.c: include magick/semaphore.h. * magick/magic.c: include magick/semaphore.h. * magick/magick.c: include magick/semaphore.h. * magick/module.c: include magick/semaphore.h. * magick/semaphore.c: include magick/semaphore.h. * magick/stream.c: include magick/semaphore.h. * magick/tempfile.c: include magick/semaphore.h. * magick/type.c: include magick/semaphore.h. * magick/blob.h (_BlobInfo): Changed `Semaphore *` to `void *`. * magick/cache.h (_CacheInfo): Changed `Semaphore *` to `void *`. * magick/image.h (_Image): Changed `Semaphore *` to `void *`. * magick/command.c: Updated each invokation of MagickMapAddEntry() to add an exception argument. * tests/maptest.c: Updated to pass an exception argument to MagickMapAddEntry. * magick/image.c (AddCoderOptions): Added exception argument and some more error handling. * magick/map.c: Added formal documentation for methods. (MagickMapCloneMap): Added exception argument. (MagickMapAddEntry): Added exception argument and status. 2003-09-22 Bob Friesenhahn * coders/emf.c: Changed NotAnEMFFile to ImproperImageHeader. * magick/map.h: Changed all size parmeters from type `unsigned long` to `size_t`. * magick/map.c (MagickMapCopyBlob): Add new function to support copying a Blob in a MagickMap. (MagickMapDeallocateBlob): Add new function to support deallocating a Blob in MagickMap. 2003-09-23 Lars Ruben Skyum * coders/ps3.c: Fixed handling the case when no -coder-options are provided to the PS3 coder. 2003-09-22 Lars Ruben Skyum * coders/ps3.c: Changed %%Creator version to use MagickLibVersionText, increased precision in HiResBoundingBox, added a coder specific option for rendering bilevel images with the PS imagemask operator indstead of the image operator. * magick/command.c: Added "-coder-options" command line argument to all relevant command line utilities. Option argument to -coder-options is a list of comma separated key-value pairs that are saved in a MagickMap in ImageInfo for (de-)coders to use. See PS3 coder for an example that checks for: -coder-options "ps:image=imagemask" * magick/image.c, magick/image.h: Added function AddCoderOptions(). * magick/map.c, magick/map.h: removed MS-DOS line terminators. 2003-09-22 Bob Friesenhahn * tests/maptest.c (main): Test/demo program for key,value map API. * magick/map.c, magick/map.h: Implementation of a key,value map API for internal use. 2003-09-19 William Radcliffe * lcms/include/icc34.h lcms.h: Added back the icc34.h header and changes to make lcms compile on Win32" icc34.h lcms.h. 2003-09-19 Lars Ruben Skyum * coders/ps3.c: Fixed warnings from Solaris compiler. 2003-09-18 Bob Friesenhahn * locale/C.mgk: Eliminated the many "NotA" messages since they may all be considered forms of "ImproperImageHeader". It is useful to provide the origin of such messages in case the wrong coder has been invoked, however, this is expensive to do via the message database since it explodes the number of messages. The exception logging can help here. Once the exception reports include the reporting entity, it will be more clear when the software misbehaves. * magick/error.h (ThrowReaderException2): Remove since no longer used. (ThrowReaderException): Simplified implementation so that ThrowException is not expanded twice. * magick/error.h (ThrowReaderException3): Remove since never used. * coders/xtrn.c (ReadXTRNImage): Use ThrowReaderException rather than ThrowReaderException2. * locale/C.mgk (MissingArgument) Updated to include %s so that the description field appears earlier in the message. * magick/error.c (DefaultErrorHandler): Added a hack to allow the `reason` member to include a %s so that it may specify the formating of the message. Care should be taken to not over-use this hack. 2003-09-18 Lars Ruben Skyum * coders/ps3.c: Major update of the PS3 coder. Now ascii85 encodes all binary data. Many printer spoolers don't like the binary data. The coder now creates much smaller files for bilevel, gray, and colormapped images. Compression and image type is now separated so they may be combined independently. Any alpha channel is separated into a separate mask so it's possible to mask bilevel, gray, colormapped, rgb, and CKYK images. You may also mask a JPEG compressed PS file for instance. Clipping masks created from a photoshop clipping path with -clip option is converted to a corresponding postscript clipping path. New functions need comment headers. * magick/attribute.c: Added TracePSClippingPath for creating a postscript clipping path from a photoshop clipping path. * magick/compress.c, magick/compress.h: Added write-hook based interface to compression functions. Required for ascii encoding compressed, binary data. The interface between blob write functions, compression functions, and encoding functions could benefit from more of this work. * magick/image.c: ClipPathImage now stores the name of the clipping path in the mask image filename so that it is remembered and may be used for creating a postscript clipping path for postscript output. * coders/modules.mgk: Added EPS3 mapping to module PS3. 2003-09-17 Bob Friesenhahn * magick/command.c: Coalesced various "Missing" error reports into one "MissingArgument" error report in order to reduce the number of messages to be maintained. * locale/C.mgk: Removed almost all "Missing" messages. * magick/gm_messages.mc: Added Microsoft message compiler source file to CVS until which time it may be generated automatically during the build. 2003-09-16 Bob Friesenhahn * locale/Makefile: Added ability to generate gm_messages.mc (for Windows message compiler) as well as adding `clean` and `install` targets. * magick/delegate.h: Visual Studio .NET 2003 doesn't like the chaining of GhostscriptVector members which share a common return type. Splitting the definitions solves this problem. 2003-09-15 Bob Friesenhahn * magick/deprecate.h (MagickSignedType): Compatibility definition to handle ImageMagick API change. (MagickUnsignedType): Compatibility definition to handle ImageMagick API change. The new names are just as useless as the old names, but at least they are shorter. * magick/command.c: Linux's sscanf has the terrible bug that it improperly handles pulling out the first floating value from the string "0x1". Instead of retrieving the value 0 and returning 1, it returns 0, probably because it rejects the string as a hex constant. As a result, all options which used sscanf to validate this input are now converted to use IsGeometry(). 2003-09-14 Bob Friesenhahn * ltdl/ltdl.c: Update to libltdl current as of today. * ltmain.sh: Update to libtool current as of today. * configure.ac: For HPUX C++ compiler, add -AA to CXXFLAGS rather than CXX. 2003-09-12 Bob Friesenhahn * configure.ac: Decided that the standards conformance defines create more problems than they solve so they are removed. Move the large-file tests to before the libtool configuration since the libtool configuration was causing stdlib.h to be included prior to the large file defines, and this causes header failure with C++ under AIX. * www/api/types.html: Update description of MonitorHandler. 2003-09-11 Bob Friesenhahn * configure.ac: Set CXX to PTHREAD_CXX if necessary (and warn). * acinclude.m4 (ACX_PTHREAD): Add check to see if xlC_r should be used for AIX. 2003-09-10 Glenn Randers-Pehrson * magick/render.c: Fixed handling of arc primitive (see IM-5.5.8). 2003-09-10 Bob Friesenhahn * magick/log.h: It seems that test programs are using GetMagickModule so make it visible by default. * configure.ac: Use GM_FUNC_MMAP_FILEIO macro to test mmap. * acinclude.m4 (GM_FUNC_MMAP_FILEIO): New macro to test mmap's capability to do coherent file I/O. The AC_FUNC_MMAP macro was not testing the mmap features that GraphicsMagick uses, and was failing on a number of systems. * magick/blob.c (BlobMapModeToString): Only include this static function if HAVE_MMAP is defined. * coders/locale.c (WriteLOCALEImage): Fix FormatString argument type inconsistencies. * wand/magick_compat.h: Change MagickExport to WandExport. * coders/jpeg.c, coders/locale.c, coders/meta.c, coders/miff.c, coders/palm.c, coders/pict.c, coders/svg.c, coders/tiff.c, coders/topol.c, magick/cache.c, magick/display.c, magick/image.c, magick/widget.c: Removed unused values, changed storage types, or added explicit casts, in order to reduce the number of "REMARK"s when using the SGI IRIX compiler. * magick/render.c (DrawClipPath): Fix memory leak of clone_info->clip_path. Problem reported by Vladimir . (DestroyDrawInfo): Remove unnecessary checks for non-null prior to invoking MagickFreeMemory. MagickFreeMemory already checks for non-null. * magick/log.h (GetCurrentFunction): Apparently Visual C++ 6.0 does not support __FUNCTION__. Problem reported by Vladimir . * wand/magick_compat.c: All functions in magick_compat.c must use WandExport rather than MagickExport. Fix recommended by Vladimir . * magick/constitute.c (PushImagePixels): number_pixels was always cast to a long during use, so change to store value in a long instead. (PopImagePixels): number_pixels was always cast to a long during use, so change to store value in a long instead. 2003-09-09 Bob Friesenhahn * coders/psd.c: Eliminated warning regarding unused initialized variable. * magick/log.c: Eliminate type warnings regarding enum assignment. * coders/locale.c (WriteLOCALEImage): Use UndefinedException rather than 0 in severity_list terminating entry in order to avoid a type conversion warning. * magick/image.c (SetImageChannelDepth): Depth parameter was being returned rather than status. Oops! * magick/effect.c (BlurScanline): Due to automatic casting conventions, computation was being done (at least with SGI compiler) as type `unsigned long` rather than `long` as it should have been. * coders/jpeg.c, coders/meta.c, coders/miff.c, coders/msl.c, coders/palm.c, coders/pcd.c, coders/psd.c, coders/svg.c, coders/tiff.c, coders/xcf.c, magick/render.c, : Quench many SGI compiler warnings regarding variables which are initialized but never used. * magick/xwindow.h: Undef gravity defines so that enumerated type is used instead. 2003-09-08 Bob Friesenhahn * magick/log.c (LogMagickEvent): Windows system logging functionality is not currently ported to work with Cygwin so disable when compiling under Cygwin. * magick/log.c (Win32EventlogOutput): Remove spurious comma in enum. * wand/drawing_wand.h: Remove junk comment marker that I forgot to remove. * magick/studio.h: Provide prototypes for strlcpy and vsnprintf if the system doesn't provide them in the requested compilation environment. * configure.ac: Add necessary standards compilance definitions to magick_config.h. Check for strlcpy and vsnprintf prototypes. * Makefile.am (DOCDIRS): www/api/types does not exist anymore. 2003-09-06 Bob Friesenhahn * configure.ac: Move multithread tests prior to libtool configuration in case value of CC is changed. Otherwise libtool gets confused and refuses to run. * acinclude.m4 (ACX_PTHREAD): If using AIX CC `xlc` use `xlc_r` for multithread compiler. * coders/jpeg.c: Undef HAVE_STDLIB_H before including the jpeg headers or else we get an already defined error/warning. 2003-09-04 Mike Chiarappa * BCBMagick : Updated whole directory tree to achieve correct compilation with Borland C++ Buider 6.0. 2003-09-04 Bob Friesenhahn * magick/image.c (ClipPathImage): Remove MS-DOS line terminations (actually, extra carriage returns) which somehow crept into ClipPathImage. * locale/C.mgk: Added message for "PNG library is too old". 2003-09-04 Lars Ruben Skyum * magick/transform.c (ProfileImage): Bugfix: conditional compilation based on LCMS being present or not now works as expected. An exception is thrown if LCMS is not present and profile conversion is used. 2003-09-04 Bob Friesenhahn * coders/txt.c (ReadTXTImage): Fix strlen() pointer type warning. * magick/image.c (TextureImage): Fixed return with no value warning. * magick/color.c (GetColorInfoArray): Decided that the const return value was a bad idea. Therefore, the return type has been made non-const. * magick/magick.c (GetMagickInfoArray): Decided that the const return value was a bad idea. Therefore, the return type has been made non-const. * tests/constitute.c, tests/rwblob.c, tests/rwfile.c : Define MAGICK_IMPLEMENTATION since these test programs using some internal extensions. * configure.ac: Test C++ compiler for __func__ support. * magick/log.h: Added GetCurrentFunction() macro to handle __func__ support determination. Re-wrote GetMagickModule() macro to use GetCurrentFunction(). Changes should allow compilation of Magick++ when the C compiler supports __func__ but the C++ compiler does not. * configure.ac: Changed from using HAS___func__ define to HAS_C__func__ since this feature may be language sensitive. * locale/C.mgk: Added missing JNGCompressionNotSupported message. 2003-09-02 Bob Friesenhahn * magick/attribute.c (Generate8BIMAttribute): Fix sscanf argument type mis-match. * coders/ps3.c (ZLIBEncodeImage): Fix mis-classified ZipLibraryIsNotAvailable error report. * coders/url.c (RegisterURLImage): Only register URL format support if libxml2 is available. * coders/msl.c (RegisterMSLImage): Only register MSL format support if libxml2 is available. 2003-09-01 Bob Friesenhahn * coders/histogram.c (WriteHISTOGRAMImage): Remove a useless loop. * coders/wpg.c: Applied patch from Fojtik Jaroslav to support reading WPGs which use the EXT token. 2003-08-31 Bob Friesenhahn * magick/color.c (HistogramToFile): Renamed static method `Histogram` to `HistogramToFile` to make it more clear what this function does. (GetColorHistogram): Added new function to support retrieving a color histogram of the image. A color histogram contains a count of how many times each color occurs in the image. * magick/image.c (GetImageChannelDepth): Return an `unsigned int` rather than `long`. 2003-08-29 Bob Friesenhahn * PerlMagick/Magick.xs: Add support for CopyCyan, CopyMagenta, CopyYellow, and CopyBlack, composition operators. * magick/composite.c (CompositeImage): Added support for CopyCyanCompositeOp, CopyMagentaCompositeOp, CopyYellowCompositeOp, and CopyBlackCompositeOp, composition operators. 2003-08-28 Bob Friesenhahn * wand/*: Updated to current ImageMagick Wand API (minus a few unimplemented functions). * magick/image.c (TextureImage): Add status return because Wand API wants it. Inherit is_grayscale status from texture image. * magick/fx.c (SolarizeImage): Add status return because Wand API wants it. * magick/resource.c (SetMagickResourceLimit): Add status return because Wand API wants it. * magick/draw.c (DrawPeekGraphicContext): Now returns a copy of the current DrawInfo context rather than returning a pointer into the context stack. The user must destroy this copy using DestroyDrawInfo() once it is no longer needed. 2003-08-25 Bob Friesenhahn * VisualMagick/filters/LIBRARY.txt: This file is necessary to incorporate analyze.c into the static build. Without it the build fails. 2003-08-23 Lars Ruben Skyum * magick/transform.c: ProfileImage updated to handle alpha channels and grayscale images. Also optimized color profiling of color mapped images and fixed a few bugs in profiling of CMYK images. * magic/locale_c.h: added MagickExport to prototype declaration of GetLocaleMessageFromID in WriteLOCALEImage again. Please update your locale coder. 2003-08-23 Bob Friesenhahn * coders/wpg.c: Applied patch from Fojtik Jaroslav to use the GetMagicInfo() function to obtain the format of embedded images, and to provide a default WPG palette if the WPG file does not supply a palette. 2003-08-22 William Radcliffe * magick\gm_messages.bin locale_c.h transform.c: Fixed missing message problem and added support for new lcms error handler. 2003-08-21 Lars Ruben Skyum * magick/attribute.c, magick/image.c, magick/command.c: Added "clippath" option for clipping named Photoshop clipping paths, increased precision in clipping path knots, added comments, and fixed a few bugs resulting from moving TraceClippingPath function from ImageMagick to GraphicsMagick. Still need to update some of the documentation. * magick/locale_c.h, magick/studio.h: added MagickExport to declaration of GetLocaleMessageFromID and moved include of magick/locale_c.h after declaration of MagickExport. This fixes a link error in dynamic, DLL version. * coders/locale.h: added MagickExport to prototype declaration of GetLocaleMessageFromID in WriteLOCALEImage. 2003-08-21 Bob Friesenhahn * PerlMagick/t/subroutines.pl (testRead): Ignore useless TIFF warning so that 12-bit TIFF test passes. * magick/constitute.c (ReadImage): Ensure that the reported image magic string is that of the user-specified input file rather than a temporary file prepared by an external delegate program. * magick/command.c (ImportImageCommand): Since DestroyExceptionInfo() now sets the destroyed exception signature to an invalid value, GetExceptionInfo(exception) must be invoked when the intention is to simply purge the exception. This fix resolves an abort when executing `gm import`. 2003-08-18 William Radcliffe * magick\gm_messages.bin locale_c.h transform.c: Updates that add latest enhancments by Lars to color management code in ProfileImage. 2003-08-19 Bob Friesenhahn * coders/wpg.c: Incorporated patch from Fojtik Jaroslav to support rendering embedded WMFs. 2003-08-18 Bob Friesenhahn * magick/image.c (SetImageChannelDepth): New function to transform the specified channel so it fits the specified modulus depth. * magick/blob.c (BlobToImage): Skip calling SetImageInfo() if magick is already set. 2003-08-18 William Radcliffe * PerlMagick/Magick.xs: Some fixes to get PerlMagick compiling again due to new ID based error macros. 2003-08-17 Bob Friesenhahn * magick/error.h (enum): Remove spurious comma. 2003-08-17 William Radcliffe * coders\png.c: Had to modify a few exception calls to work with newest macros. 2003-08-17 William Radcliffe * coders\locale.c magick/error.h locale.c locale_c.h studio.h: The LOCALEH header file generator now adds an MGK_ prefiix to all the ID defines as part of a fix to support the new error and exception macros cross platform. 2003-08-16 William Radcliffe * wand\magick_wand.c pixel_wand.c: The wand api code was totally left out of the large macro conversion below as an oversight. 2003-08-15 William Radcliffe * .\coders art.c avi.c avs.c bmp.c caption.c clipboard.c cmyk.c cut.c dcm.c dib.c dps.c dpx.c emf.c ept.c fax.c fits.c fpx.c gif.c gradient.c gray.c hdf.c histogram.c html.c icon.c jbig.c jp2.c jpeg.c label.c locale.c logo.c map.c mat.c matte.c meta.c miff.c mono.c mpc.c mpeg.c msl.c mtv.c mvg.c null.c otb.c palm.c pcd.c pcl.c pcx.c pdb.c pdf.c pict.c pix.c png.c pnm.c preview.c ps.c ps2.c ps3.c psd.c pwp.c rgb.c rla.c rle.c sct.c sfw.c sgi.c stegano.c sun.c svg.c tga.c tiff.c tile.c tim.c topol.c ttf.c txt.c uil.c url.c uyvy.c vicar.c vid.c viff.c wbmp.c wmf.c wpg.c x.c xbm.c xc.c xcf.c xpm.c xtrn.c xwd.c yuv.c .\magick\animate.c annotate.c blob.c cache.c cache_view.c color.c color.h command.c compress.c constitute.c decorate.c delegate.c display.c draw.c effect.c enhance.c error.c error.h fx.c gm_messages.bin image.c list.c locale.c locale_c.h log.c mac.c magic.c magick.c module.c montage.c nt_feature.c paint.c quantize.c registry.c render.c resize.c segment.c semaphore.c shear.c signature.c static.c static.h stream.c studio.h tempfile.h transform.c type.c utility.c widget.c xwindow.c : Changes to support ID based message access and checking all message usages. The main thing that was done was to remove all the quotes around the "tags" used to lookup messages defined in the locale\C.XML file. Macros were added to error.h to allow the code to be compiled for either string based access or binary ID based access. Using binary ID's will cause the code to fail to compile if a message does not exist in C.XML, since no ID will be created for a missing message. This change then allowed us to easily track down all the messages that were "missing" or not being accessed properly. The problems were massive and took many days to resolve. I have left the code compiling in ID mode to keep things in sync going forward and also because it makes message lookup instantaneous. An ID is just an index into and array of char *'s. There is still a lot of cleanup work remaining, but this is a very good start. 2003-08-14 Bob Friesenhahn * magick/error.c (GetLocaleExceptionMessage): Add check to avoid duplicating severity prefix. * magick/log.c (LogMagickEvent): Incorporated fix from Bill Radcliffe to enable logging control flags to work properly again. * NEWS: Updated news. * magick/blob.c (OpenBlob): Rewind file descriptor so that first read is at zero offset. This fixes reading GIFs via a user-provided file handle. 2003-08-13 Bob Friesenhahn * magick/image.c (GetImageDepth): Extend so that the actual minimum depth required to represent the image is returned. Previously only the values 8, 16, and 32 were returned. This means that a value of one is returned for a monochrome image. Also fixed a bug in that the pixels were incremented while the depth was incremented, resulting in the first image pixels not being properly evaluated for depth. (SetImageDepth): Extend to support converting the image to arbitrary modulus depths. (GetImageChannelDepth): New function to obtain the modulus depth for a specified image channel. 2003-08-12 Bob Friesenhahn * magick/draw.c (MvgAutoWrapPrintf): StreamError reported when DrawError was intended. * coders/logo.c (ReadLOGOImage): Report FileOpenError rather than BlobError if requested image does not exist. 2003-08-10 Bob Friesenhahn * magick/cache.c (PersistCache): If HAVE_SYSCONF and _SC_PAGE_SIZE are defined, then assume that sysconf works and don't use legacy getpagesize() function. * magick/studio.h (_XOPEN_SOURCE): Should be defined as 600 in order to match _POSIX_C_SOURCE=200112L according to the Single UNIX Specification v3. This is necessary for the vsnprintf prototype to be visible. * magick/attribute.c (ReadByte): Fix compilation warnings due to casting `unsigned char *` to `char *` by changing function definition to accept `unsigned char *` instead. * magick/error.h (UndefinedException): UndefinedException should be ExceptionType, not ExceptionBaseType. * magick/magick.c (IsValidFilesystemPath): Eliminate warning about unused function when UseInstalledMagick is defined. * magick/error.c (ThrowLoggedException): Fix improper parameters passed to LogMagickEvent() when reason is not available. 003-08-07 William Radcliffe * magick/log.c, log.h: Added ability to log by either severity or by category of event. Made the defualt on windows to log all fatal errors, errors, and warnings to the event log. This will include anything generated by exceptions currently, but not any normal "informational" logging. 2003-08-07 William Radcliffe * magick/log.c, log.h: Translation of event codes to mask vals was not working. Code was left out of last update. It is now in. 2003-08-07 William Radcliffe * magick/error.c: Protect against NULL string passed into the message lookup function. 2003-08-07 William Radcliffe * magick/locale.c: Switched use of IsAccessible to nonloggging version to prevent recursive problems. 2003-08-06 Bob Friesenhahn * magick/Makefile.am (noinst_HEADERS): Distribute locale_c.h. * locale/Makefile: Output locale_c.h. * utilities/gm.c (main): Fix typo in Unix InitializeMagick invocation. * configure.ac: Use ACX_PTHREAD pthreads test macro. * magick/(semaphore.c,spinlock.h,studio.h): Change HasPTHREADS conditional define to HAVE_PTHREAD. * magick/Makefile.am (noinst_HEADERS): Include spinlock.h in distribution. 2003-08-06 William Radcliffe * contrib\win32\ATL7\ImageMagickObject/ImageMagickObject.cpp, ImageMagickObject_.h, ImageMagickObject.def, ImageMagickObject.rc gm.rc: Changes to get things compiling again since all windows specific logging support has been eliminated. The special build script BuildImageMagickObject.cmd now compiles the message file for resource based messages. The result is in gm_messages.bin. The script also generates a special version of gm.exe that uses the COM dll as a regular DLL and links to it. This is the long desired Moby DLL build idea. * magick/error.c, magick/error.h, magick/log.c, magick/log.h: Upgrade of logging system to take over previous special logging code for windows in nt_base.c. The new logic provides logging of events to the debug api and the windows event log and also provides a generic text file logging method. * magick/gm_messages.bin, magick/ImageMagick.rc: New compiled message file based on data in locale\C.mgk. RC file modified to include this as a resource. * magick/locale.c, magick/locale_c.h: locale_c.h is generated by the LOCALEH format of the locale coder. The logic in locale.c uses the tables in the header lookup messages. On windows, all the messages are stored as resources, while on UNIX they remain in a string table. * locale/C.mgk: Removed duplicate messages and added some new default messages that help to create a complete set of severity strings. * magick/command.c, magick/magick.c: Get rid compiler warnings. 2003-08-05 William Radcliffe * magick/command.c, magick/gm.c: Application level changes to implement the client name - filename changes. The client name can now be anything that the application wants and has nothing to do with the saved filename of the application. * magick/nt_base.c, magick/nt_base.h, magick/magick.c: Ripped out old nt specific debugging and logging logic. Moving to the standard logging. New and major revisions to InitializeMagick to make the code more maintainable, reliable, and reaable. It should be functionally identical, but implements the new split client name and filename methododology. * magick/utility.c, magick/utility.h: Added a couple of new routines to support splitting the overloaded use of the client name and client filename. * coders/xtrn.c: Minor code cleanup 2003-08-05 Bob Friesenhahn * Copyright.txt: Added missing copyright notice which is required due to copying the rlecomp manual page into ImageMagick. * doc/config_files.imdoc: Started documentation for configuration files. * magick/xwindow.c (XSignalHandler): Ensure that segment_info is non-null before attempting to use it. Much thanks to John Cristy for bringing this problem to our attention. 2003-08-05 William Radcliffe * coders/locale.c: Added several new formats to this coder to generate windows message resource format messages and also to generates a new header file format that will support a table based version of the other magick/locale.c. * coders/xtrn.c: Minor code cleanup 2003-08-03 Bob Friesenhahn * configure.ac: Only configure C and C++ libtool tags. * PerlMagick/t/reference/composite/*.miff: Added some composition test reference images. These reference images will serve as placeholders until better composition tests can be figured out. It is not clear from the documentation what some of the composition operators are supposed to do. 2003-08-01 Bob Friesenhahn * README.txt: Add documentation regarding using TRIO. * configure.ac: Test for TRIO library if vsnprintf is not available. * magick/studio.h: Remap vsnprintf to trio_vsnprintf if TRIO is available. * coders/topol.c, coders/wmf.c, magick/magick.c, magick/nt_base.c, magick/resource.c: Use traditional C comment form in C source files. 2003-07-31 Bob Friesenhahn * magick/log.h (LogEventType::AllEvents): Increase the value of AllEvents so that it spans the complete positive range of a signed integer. * magick/xwindow.c, magick/xwindow.h: Incorporate patch from John Cristy's ImageMagick to eliminate conditional dependence of magick/xwindow.h on . * magick/magick_config_api.h.in: HasSharedMemory define no longer needed. 2003-07-30 Bob Friesenhahn * www/programming.html: Update Rmagick URL. * GraphicsMagick.spec.in : Update according to instructions from Troy Edwards. 2003-07-29 Bob Friesenhahn * GraphicsMagick.spec.in: Replaced GraphicsMagick.spec with GraphicsMagick.spec.in, which is configured to produce GraphicsMagick.spec. * configure.ac: Configure GraphicsMagick.spec. 2003-07-29 Troy Edwards * GraphicsMagick.spec: Updated to CVS build. Added the GraphicsMagickWand files to the spec. Only try to remove the unneeded perl package files if we are using PerlMagick. 2003-07-28 Bob Friesenhahn * GraphicsMagick.spec: Added RPM spec file authored by Troy Edwards . * NEWS: Add note regarding EXIF fix. * magick/attribute.c (GenerateEXIFAttribute): Look for the profile name "EXIF" rather than "APP1". 2003-07-26 Bob Friesenhahn * magick/magick_config_api.h.in: XWindowInfo structure in xwindow.h needs HasSharedMemory define. * magick/xwindow.c, magick/xwindow.h: Move inclusion of to xwindow.c. * coders/dps.c, magick/xwindow.h: Move DPS includes to coders/dps.c * coders/Makefile.am: Substituted values are also set as make variables, so use variables rather than substitutions. * magick/log.c (GetLogBlob): MAGICK_HOME needs to take precedence over the client path for the uninstalled build. * magick/type.c (GetTypeBlob): MAGICK_HOME needs to take precedence over the client path for the uninstalled build. * magick/blob.c (GetConfigureBlob): MAGICK_HOME needs to take precedence over the client path for the uninstalled build. * magick/module.c (FindMagickModule): MAGICK_HOME needs to take precedence over the client path for the uninstalled build. 2003-07-24 Lars Ruben Skyum * magick/attribute.c (TraceClippingPath): Improvements to clipping path parsing. 2003-07-17 Bob Friesenhahn * magick/cache.c: Disable the Windows open() extensions when compiling using Borland C++. * magick/log.c (LogMagickEvent): Unlock semaphore before returning. * ltdl/ltdl.h: Updated to latest CVS version. * ltdl/ltdl.c: Updated to latest CVS version. * Libtool: Updated to use latest CVS libtool. 2003-07-17 Mike Chiarappa * BCBMagick: Contributed initial Borland C++ Builder 6.0 build environment. 2003-07-13 Bob Friesenhahn * magick/color.c (GetColorInfoArray): Added a function to access the color definition list as an array. (GetColorList): Added access locks to ensure that list is not re-ordered while it is being traversed. * www/Magick++/Image.html: Add some more information regarding raw pixel access. 2003-07-12 Bob Friesenhahn * wand/GraphicsMagickWand.pc.in (Cflags): Remove LFS_CPPFLAGS. * wand/GraphicsMagickWand-config.in: Remove LFS_CPPFLAGS. * magick/GraphicsMagick.pc.in (Cflags): Remove LFS_CPPFLAGS. * magick/GraphicsMagick-config.in: Remove LFS_CPPFLAGS. * configure.ac: Logic for setting LFS_CPPFLAGS was incomplete. * coders/topol.c: Updated topol coder contributed by Jaroslav Fojtik. Topol is coming to life! 2003-07-10 Bob Friesenhahn * magick/nt_base.h: Add a typedef for ssize_t * magick/deprecate.h: ExtendedSignedIntegralType and ExtendedUnsignedIntegralType are now deprecated types so they are moved to deprecate.h. Existing code which uses these types should continue to work. * magick/blob.c (MapBlob): Change `offset` parameter from type off_t to magick_off_t so that it is not LFS dependent. * magick/cache.c (GetPixelCacheArea): Return magick_off_t. (PersistCache): Change `offset` parameter to type magick_off_t. * magick/cache.h (NexusInfo): Change `length` type from ExtendedSignedIntegralType to magick_off_t. (CacheInfo): Change `offset` and `length` types from ExtendedSignedIntegralType to magick_off_t. * magick/blob.c (BlobToFile): Use ssize_t rather than ExtendedSignedIntegralType for count. (TellBlob): Return magick_off_t rather than ExtendedSignedIntegralType. * configure.ac: Check for a ssize_t type. * magick/blob.h (_BlobInfo): Change `offset` and `size` members from ExtendedSignedIntegralType to magick_off_t. * magick/blob.c (GetBlobSize): Return magick_off_t rather than ExtendedSignedIntegralType. (SeekBlob): Accept and return magick_off_t rather than ExtendedSignedIntegralType. 2003-07-09 Bob Friesenhahn * magick/monitor.c (MagickMonitor): Change `quantum` argument from type ExtendedSignedIntegralType to magick_int64_t. Change `span` argument from ExtendedUnsignedIntegralType to magick_uint64_t. * magick/xwindow.c (XMagickMonitor): Change `quantum` argument from type ExtendedSignedIntegralType to magick_int64_t. Change `span` argument from ExtendedUnsignedIntegralType to magick_uint64_t. * magick/widget.c (XMonitorWidget): Change `quantum` argument from type ExtendedSignedIntegralType to magick_int64_t. Change `span` argument from ExtendedUnsignedIntegralType to magick_uint64_t. * magick/studio.h (QuantumTick): Change typecast from ExtendedSignedIntegralType to magick_int64_t. * magick/resource.c (AcquireMagickResource): Change `size` argument type from ExtendedSignedIntegralType to magick_int64_t. (LiberateMagickResource): Change `size` argument type from ExtendedSignedIntegralType to magick_int64_t. * magick/utility.c (FormatSize): Change `size` argument type from ExtendedSignedIntegralType to magick_int64_t. * magick/nt_base.c: Change MagickOffset to magick_off_t. * magick/studio.h (magick_off_t): Change MagickOffset to magick_off_t. * coders/topol.c: Insert dummy member into palettRAS structure since Visual C++ doesn`t seem to handle empty structures. * wand/GraphicsMagickWand.pc.in (prefix): Pass LFS CPPFLAGS. * wand/GraphicsMagickWand-config.in: Pass LFS CPPFLAGS. * wand/Makefile.am: Fix include path. * magick/GraphicsMagick.pc.in (prefix): Pass LFS CPPFLAGS. * magick/magick_config_api.h.in: Pass LFS configuration options until the API is fixed so that it is not LFS sensitive anymore. * magick/GraphicsMagick-config.in: Pass LFS CPPFLAGS. * PerlMagick/Makefile.PL.in: Pass LFS CPPFLAGS. * magick/Makefile.am: Install magick_types.h. * magick/api.h: Include magick_types.h. * magick/studio.h: Include magick_types.h rather than integral_types.h. * VisualMagick/magick/magick_types.h.in: New header file (replacing integral_types.h) to contain CPU and system-dependent primitive typedefs. * magick/magick_types.h.in: New header file (replacing integral_types.h) to contain CPU and system-dependent primitive typedefs. * configure.ac: Use AC_SYS_LARGEFILE to test for large file options. Update to determine integral typedefs for current CPU and compiler options. Configure magick_types.h. * magick/attribute.c (TraceClippingPath): Apply patch from Lars Ruben Skyum which fixes clipping path parsing for paths generated by Adobe software which pre-dates the Photoshop file format specification. 2003-07-08 William Radcliffe * magick/semaphore.c: Modified the way the system handles the initialization of Win32 critical sections to use a spin lock on WIn32 to bootstrap the initialization of all other crtical sections. This is not an issue on UNIX since static init is used. * magick/magic.c module.c magick.c log.c resource.c constitute.c color.c cache.c delegate.c registry.c type.c: Small modifications were made to eliminate the side effect of unlocking semaphores as part of the releasing procedure. This also eliminated the apparent bug of the system double locking certain semaphores. The locked flag should now not be needed, but remains in place for the time being as an added safegaurd. 2003-07-04 Glenn Randers-Pehrson * png.c: added missing #ifdef JNG_SUPPORTED/#endif directives. 2003-07-04 Bob Friesenhahn * NEWS: Updated news to include fixes and enhancements since the 1.0 release. 2003-07-03 Bob Friesenhahn * magick/semaphore.c (UnlockSemaphoreInfo): Bugfix, modify the `locked` flag while still under protection of the lock. This fix is necessary for thread-safety. 2003-07-02 Bob Friesenhahn * coders/jpeg.c (ReadJPEGImage): Conditionally copy exception. * wand/Makefile.am (noinst_HEADERS): Need to distribute magick_compat.h. (EXTRA_DIST): Need to distribute GraphicsMagickWand-config.1. * coders/wmf.c (ipa_bmp_draw): Use CopyException. (ipa_device_begin): Use CopyException. (lite_font_map): Use CopyException. * coders/jpeg.c (ReadJPEGImage): Use CopyException. * magick/image.c (GetImageException): Use CopyException. * magick/constitute.c (WriteImages): Use CopyException. * Makefile.am (DIST_SUBDIRS): wand needs to be included in distribution. 2003-06-30 Bob Friesenhahn * magick/static.c (RegisterStaticModules): Invoke RegisterTOPOLImage. * magick/magick.h (MagickInfo): Add member usage comments. * magick/error.c (CatchException): Restore saved errno from exception->error_number. (CopyException): Copy error_number. (DestroyExceptionInfo): Reset error_number to zero. (GetExceptionInfo): Initialize error_number to zero. (ThrowException): Save errno to exception-> error_number. (ThrowLoggedException): Save errno to exception-> error_number. * magick/error.h (ExceptionInfo): Borrow John Cristy's idea and add a error_number member to ExceptionInfo to save the current errno value. Otherwise CatchException may use some random errno. * coders/Makefile.am: Build topol.c. * coders/topol.c: Added initial TOPOL X image coder which is under development by Jaroslav Fojtik. Not working yet. 2003-06-29 Bob Friesenhahn * coders/pwp.c (ReadPWPImage): Ensure that image is initialized before invoking ThrowReaderException. * magick/image.c (CloneImage): Use CopyException. * magick/error.c (CopyException): Add function to support copying ExceptionInfo structures. * magick/error.h (ExceptionInfo): Replaced recently-added `whence` member with module, function, and line members in order to keep the information seperate, and match the parameters used by the logging system. (ThrowException): Log thrown exceptions. * magick/error.c (ThrowLoggedException): New function used to throw an exception, while recording and logging the location where the exception is thrown. * doc/options.imdoc (operation): Document TemporaryFile and Exception events. * magick/log.c (LogMagickEvent): Support logging ExceptionEvent. * PerlMagick/Magick.xs: Added "Exception" event type. * magick/log.h (LogEventType): Added ExceptionEvent. 2003-06-26 Bob Friesenhahn * magick/error.c (ThrowException): Handle `whence` member. MagickFreeMemory already checks for null pointer so don't check again. (DestroyExceptionInfo): Handle `whence` member. MagickFreeMemory already checks for null pointer so don't check again. * magick/error.h (ExceptionInfo): Add a `whence` member to support the ability to record where the exception is was thrown. * VisualMagick/installer: Install Wand files. 2003-06-25 Bob Friesenhahn * magick/blob.c (GetConfigureBlob): GetConfigureBlob should always return a value. * magick/type.c (GetTypeBlob): GetTypeBlob should always return a value. * magick/log.c (GetLogBlob): GetLogBlob should always return a value. * magick/magick.c (GetMagickInfoArray): Fixed array memory allocation and clearing bug. Eliminate warnings. 2003-06-24 Bob Friesenhahn * VisualMagick/installer/inc/files-configs.isx: For a static build, install the configuration files directly into the application directory. * VisualMagick/installer/inc/uninstallrun-unregister-com.isx (Filename): Change ImageMagickObject.dll path. * VisualMagick/installer/inc/run-register-com.isx (Filename): Change ImageMagickObject.dll path. * VisualMagick/installer/inc/files-com.isx (Source): Install ImageMagickObject.dll and MagickCMD.exe in the application directory alongside gm.exe and the CORE DLLs. * INSTALL-unix.txt: Add additional information regarding LZW. * VisualMagick/magick/magick_config.h.in: Add additional notes regarding UNISYS LZW patent. * PerlMagick/Magick.xs: Applied Dissolve composite operator fix obtained from from John Cristy's ImageMagick which ensures that an unused matte channel is set to Opaque, and uses this knowledge to simplify the math. * VisualMagick/configure/configure.cpp: The `wand` library has a linkage dependency on the `magick` library. Also don't include the magick subdirectory so that headers must be included like for safety. * coders/xtrn.c: Fix magick header inclusion. * lcms\src\cmserr.c: Fix magick header inclusion. 2003-06-23 Bob Friesenhahn * doc/options.imdoc: Fix to formatting. Fix spelling of origin. * PerlMagick/t/bzlib/read.t: Add test for reading BZipped file. * PerlMagick/t/subroutines.pl (testRead): Skip testing reads of compressed BLOBs because reading compressed BLOBs is not supported yet. * coders/bmp.c (ReadBMPImage): Only validate the file size value for compressed BMPs. * VisualMagick/wand, wand: First stab at building the Wand API under Visual C++. Still does not build as a DLL. 2003-06-22 Bob Friesenhahn * magick/static.h: Add prototypes for RegisterXTRNImage and UnregisterXTRNImage. * Makefile.am (DISTDIRS): Don't distribute the `guide` subdirectory. It is available for checkout from CVS. * www: Utilities documentation is updated from masters. Formatting could be improved, but the content seems ok. * doc/environment.imdoc: New file to describe environment variables. * coders/cut.c (ReadCUTImage): Use MagickAllocateMemory and MagickFreeMemory rather than malloc and free. * doc/gmdoc2html: Add GraphicsMagick styling to utility web pages. * doc/Makefile: Additional documentation Makefile enhancements. * AUTHORS: New file to acknowledge significant contributors to the software. If an author is not listed here, please let us know. * configure.ac: test -a is not POSIX compliant. 2003-06-17 Bob Friesenhahn * doc: Source documentation for `gm` is now available via a `doc` CVS module. A Makefile is provided which formats the documentation and installs it into the `www` and `utilities` subdirectories. 2003-06-15 Bob Friesenhahn * wand: Added Magick Wand library available via -lGraphicsMagickWand and . Use GraphicsMagickWand-config or GraphicsMagickWand.pc to obtain the compilation options required to use the library. Magick Wand is authored by John Cristy. Magick Wand is provided as a separate library from -lGraphicsMagick in order to assure the stability of the core GraphicsMagick library while allowing Magick Wand to to evolve. * images: Replace existing logo images with cleaner ones. * www: Update links to point to updated logo images. * logos: New CVS directory to contain master logos. * scripts/txt2html: Updated inline logo image link. * scripts/format_c_api_docs: Updated inline logo image link. * version.sh: Support versioning all libraries independently. * coders/meta.c: Prefix include paths for safety. * magick/image.h: (TransmitType) Removed unused enumeration. (ProfileType) Removed unused enumeration. (QuantumType) Moved enumeration to constitute.h (StorageType) Moved enumeration to constitute.h * magick/draw.c (DrawPeekGraphicContext): Added function to peek at head of drawing context stack (function added for ImageMagick compatability). * magick/image.c (CycleColormapImage): Change return type from `void` to `unsigned int` so that error status is returned to user. (DescribeImage): Change return type from `void` to `unsigned int` so that error status is returned to user. * magick/list.c (ReplaceImageInList): Incorporated function from John Cristy's ImageMagick to replace current image in the list. * coders/sgi.c (ReadSGIImage): Applied patch from John Cristy's ImageMagick to save the compression type for SGI images. 2003-06-12 Bob Friesenhahn * coders/txt.c (WriteTXTImage): Apply patch from John Cristy's ImageMagick to observe image depth while writing pixel colors. This patch is not applied to the 1.0 branch because it represents an output format change which could break a dependent application. (IsTXT): Recognize files written by the TXT coder. (ReadTXTImage): Reject files written by the TXT coder until support for reading these files is implemented. (IsTXT): Ensure that sscanf doesn't read outside of provided data by using a fixed size buffer. 2003-06-10 Bob Friesenhahn * configure.ac: Don't add -lfpx to LIBS while configuring because the C compiler may fail to link with it in later tests. 2003-06-07 Bob Friesenhahn * PerlMagick/Magick.xs: RotateImage is documented to take `degrees` argument, not `degree`. SwirlImage is documented to take `degrees` argument, not `degree`. SolarizeImage is documented to take a `threshold` argument, not `factor`. Wave is documented to take `amplitude` and `wavelength` arguments. Don't transform colorspace to RGB when retrieving `pixel` color value. Release memory acquired to store `length` pointer. Picked up memory leak fix related to `SV **reference_vector` variable from John Cristy's ImageMagick. * configure: Incorporate patch to handle inline better. * magick/utility.c (GetToken): Adjust code to avoid "end-of-loop code not reached" warning. * magick/log.c (GetLogBlob): Eliminate warning regarding unreached code. * magick/command.c (AnimateImageCommand): Eliminate warning regarding unreached code. (ConvertImageCommand): Eliminate warning regarding unreached code. (ImportImageCommand): Eliminate warning regarding unreached code. * magick/type.c (GetTypeBlob): Eliminate warning regarding unreached code. * magick/blob.c (GetConfigureBlob): Eliminate warning regarding unreached code. * coders/meta.c (super_fgets): Eliminated warnings regarding comparison and return of incompatible pointer types. (super_fgets_w): Eliminated warnings regarding comparison and return of incompatible pointer types. * magick/command.c (ConvertImageCommand): Eliminate warnings noticed when using Sun's compiler. 2003-06-06 Bob Friesenhahn * acinclude.m4: Add `#undef inline` in front of C++ tests. * coders/x.c (RegisterXImage): Only register the X coder if HasX11 is defined. 2003-06-07 Glenn Randers-Pehrson * magick/image.c (GetImageGeometry) Y was a function of width instead of height when processing EastGravity or WestGravity (bug report from Cristy). 2003-06-06 Bob Friesenhahn * magick/utility.c (LocaleNCompare): Documented that comparison is case-insensitive. (LocaleCompare): Documented that comparison is case-insensitive. * magick/log.c (ParseEvents): LocaleNCompare already does case-insensitive compare so lower-casing is not necessary. * Magick++: Updates to cause exceptions to be thrown if a bad geometry specification is supplied. 2003-06-05 Bob Friesenhahn * magick/log.c (ReadConfigureFile): Move event parsing to ParseEvents funtion. (SetLogEventMask): Move event parsing to ParseEvents funtion. * magick/utility.c (GetGeometry): Validate that the geometry string only contains valid characters. * PerlMagick/t/subroutines.pl (testMontage): It seems that passing an empty set of options to the SetImage method corrupts the image options (surely a PerlMagick bug), so don't invoke SetImage unless there are options to set. 2003-06-04 Bob Friesenhahn * magick/command.c (VersionCommand): Add build information to version output. * configure.ac: Save configure/build parameters for later use in version output. 2003-06-04 William Radcliffe * coders/meta.c: Added some casts to make things compile better. 2003-06-03 William Radcliffe * coders/meta.c: Was broken due to editing mistakes as well as inherent incompatability with MagickReallocMemory macro. 2003-06-03 Bob Friesenhahn * coders/xpm.c (RegisterXPMImage): Module registration for PICON should have been XPM. Thanks to John Cristy for noticing this bug. * coders/psd.c (ReadPSDImage): Applied John Cristy's patch to fix a index calculation bug which is evident when QuantumDepth>8. 2003-06-02 Bob Friesenhahn * coders/meta.c: Eliminated some compiler warnings. * magick/transform.c (ProfileImage): Eliminated some compiler warnings. * magick/static.c (RegisterStaticModules): Invoke RegisterXTRNImage if _VISUALC_ is defined. 2003-06-02 William Radcliffe * utilities/gm.c: made -format work again but had to add off flag to MagickCommand to maintain backward compatability with previous versions of GM. * magick/command.c: Added flag to tell MagickCommand whether GM is expected to process metadata requests. The COM object *always* does. * magick/transform.c: Added error handling, memory leak avoidance and performanc enhancment. 2003-06-01 Glenn Randers-Pehrson * NEWS: Added Bug Fixes item with info about the JNG encoder fix. 2003-06-01 Bob Friesenhahn * NEWS: Listed significant changes (thus far) in version 1.1. * version.sh: Updated LIBRARY_CURRENT and LIBRARY_REVISION since some command.c interfaces have changed, and a new interface has been added. The only user of these interfaces should be `gm` but it always pays to be careful. * utilities/gm.c (main): Use MagickCommand. * magick/command.c (MagickCommand): New function to provide API-level command access to the command functions provided by the GM utility with an interface similar to ConvertImageCommand. (AnimateImageCommand): Changed function arguments to match ConvertImageCommand. (ConjureImageCommand): Changed function arguments to match ConvertImageCommand. (DisplayImageCommand): Changed function arguments to match ConvertImageCommand. (ImportImageCommand): Changed function arguments to match ConvertImageCommand. * libxml/libxml2.def: Remove LIBRARY line since Visual C++ 6.0 doesn't like that the build library doesn't match the name specified by LIBRARY. 2003-05-31 Bob Friesenhahn * magick/magick.c (GetMagickInfoArray): Resolve thread-safety issue by accessing magick_list directly under the protection of a lock rather than using the pointer returned by GetMagickInfo. Added error handling for insufficient memory. * coders/tile.c (RegisterTILEImage): Added a usage note in formats listing. * coders/viff.c (RegisterVIFFImage): Module definition for "XV" was missing. * coders/ps2.c (RegisterPS2Image): Module definition for "PS2" was missing. * coders/wmf.c (RegisterWMFImage): Added usage note in formats listing. * coders/xpm.c (RegisterXPMImage): Hide PM alias for XPM in the formats listing. * coders/logo.c (RegisterLOGOImage): Hide registrations for GRANITE, LOGO, and NETSCAPE in the formats listing. * coders/jpeg.c (RegisterJPEGImage): Module definition for "JPEG" was missing. * coders/html.c (RegisterHTMLImage): Module definition for "HTML" was missing. * coders/bmp.c (RegisterBMPImage): Module names for "BMP2" and "BMP3" should be "BMP". 2003-05-30 Bob Friesenhahn * magick/magick.c (GetMagickInfoArray): New function to return MagickInfo array. (ListMagickInfo): Updated to use GetMagickInfoArray. (ListModuleMap): New function to list module map to a file. * utilities/gm.c: Centered the file header and made note of this stupendously significant accomplishment. * magick/command.c: Added a `-list modulemap` option. Added plural forms of other list options for people who are are not limited to the singular. Also `-list font` and `-list fonts` now work for people who think in terms of fonts rather than type. 2003-05-30 Glenn Randers-Pehrson * MNG encoder failed to set the JNG bit in the simplicity profile. * MNG encoder failed to write FRAM chunks when all images were JNG. * JNG encoder wrote the wrong alpha_sample_depth for opaque images. 2003-05-29 Bob Friesenhahn * magick/magic.c (ReadConfigureFile): Removed bogus embedded magic data and ensured that errors with loading magic.mgk propogate to the top. * magick/constitute.c (ReadImage): When building delegate error report, handle the case where the filename is empty (such as for "LOGO:"). * coders/png.c (WritePNGImage): Ensure that most severe exception is reported via exception argument. (ReadMNGImage): Ensure that most severe exception is reported via exception argument. * magick/command.c (ConvertImageCommand): Ensure that most severe exception is reported via exception argument. (CompositeImageList): Ensure that most severe exception is reported via exception argument. (CompositeImageCommand): Ensure that most severe exception is reported via exception argument. * magick/constitute.c (WriteImages): Ensure that most severe exception is reported via exception argument. * utilities/gm.c: Centered file header because I didn't like it. * locale/C.mgk: Removed some defunct messages. * magick/blob.c (PingBlob): Report useful error message. (BlobToImage): Report sensible error message for null blob. * magick/utility.c (AcquireString): Change UnableToAquireString to UnableToAllocateString. * coders/xwd.c (ReadXWDImage): Report CorruptImage rather than CorruptXWDImage. * coders/xpm.c (ReadXPMImage): Report CorruptImage rather than CorruptXPMImage. * coders/xcf.c (load_level): Report CorruptImage rather than CorruptXCFImage. * coders/wbmp.c (ReadWBMPImage): Report CorruptImage rather than CorruptWBMPImage. * coders/pcd.c: Report CorruptImage rather than CorruptPCDImage. * coders/otb.c (ReadOTBImage): Report CorruptImage rather than CorruptOTBImage. * magick/constitute.c (ReadInlineImage): Report CorruptImage rather than CorruptInlineImage. * coders/pdb.c (ReadPDBImage): Incorporated undocumented fix from ImageMagick which obtains the image depth from the image depth attribute, and increases the packet memory allocation. Report CorruptImage rather than CorruptPDBImageFile. 2003-05-28 Bob Friesenhahn * VisualMagick/bin/modules.mgk: Add mapping from SVGZ to SVG. * coders/modules.mgk: Add mapping from SVGZ to SVG. * coders/svg.c (RegisterSVGImage): Add registration for SVGZ format. * PerlMagick/t/zlib/read.t: Added test to check reading a file with .gz extension. The blob portion of the test currently fails. * coders/wpg.c (ReadWPGImage): Fix reading WPGs with embedded Postscript. Ensure that scene numbers are sane. Bugs remain. * magick/blob.c (OpenBlob): Recognize the .svgz extension as a gzipped format. Not required in order to read .svgz files since the blob file magic detects gzip files. * magick/command.c (MontageImageCommand): Wrong exception macro was being invoked. Steps have been taken to ensure that this doesn't happen again. (ImportUsage): Fix spelling of `type`. * magick/magick.c (DestroyMagick): Decided that initialization state should be tracked via an enum so that DestroyMagick will take effect even if InitializeMagick has never been called. 2003-05-27 Glenn Randers-Pehrson * coders/png.c: png.c would dump core when writing a grayscale image in png24 or png32 format. 2003-05-26 Bob Friesenhahn * coders/ept.c (WriteEPTImage): Fixed writing EPT preview image and added logging. * magick/enhance.c (NegateImage): If image is in CMYK colorspace, then negate the `K` channel as well. * PerlMagick/Magick.xs: Fix spelling of `elevation` argument to Shade method. * magick/image.h (ImageInfo): Added more documenting comments. * magick/image.c (CloneImage): Don't clone huffman ascii85 encoding support structure since it is not useful outside of the current image context. Cloning a structure via pointer assignment causes a memory leak. 2003-05-25 Bob Friesenhahn * magick/shear.c: Incorporate math tweaks obtained from ImageMagick which are purported to improve accuracy when rotating and shearing using small angles. Also avoid unneccessarily transforming CMYK images into RGB images. * magick/paint.c (ColorFloodfillImage): Fix hang while floodfilling using a pattern image with color similar to the border color. * coders/modules.mgk: Add missing mappings for PNG8, PNG24, and PNG32. * VisualMagick/bin/modules.mgk: Add missing mappings for PNG8, PNG24, and PNG32. 2003-05-23 Bob Friesenhahn * magick/log.c (GetLogBlob): Return an error if log.mgk can not be accessed. * locale/C.mgk: Added UnableToAccessLogFile. * magick/blob.c (GetConfigureBlob): Only return result of NTResourceToBlob if it is non-NULL. * magick/type.c (GetTypeBlob): Search $MAGICK_HOME for type.mgk. Only return result of NTResourceToBlob if it is non-NULL. * magick/magick.c (GetMagickInfo): Return an error if GetModuleInfo reports an error. * magick/module.c (GetModuleInfo): Return an error if modules.txt fails to load. * utility.c (SubstituteString): Fixed a bug which was introduced while updating the code to use the memory allocation macros. 2003-05-22 Bob Friesenhahn * magick/GraphicsMagick-config.in (usage): Added example usage to the help output. * magick/magick.c (InitializeMagick): Added a static flag to ensure that the Magick library is initialized only one time. (DestroyMagick): Ensure that Magick library resources are only destroyed if it has previously been initialized. * magick/nt_base.c (DllMain): Fix contributed by Achim Domma. For a DLL build, update PATH during Magick DLL initialization to include the directory where the Magick core DLL resides. This allows the loadable modules to find the core DLLs, even if the core DLLs are not already in the PATH. * magick/image.c (TextureImage): Incorporate new implementation authored by John Cristy of ImageMagick Studio. This implementation is a full 7X (run-time) or 14X (user-time) faster than the original ImageMagick implementation, and is about 2X faster than the speeded-up version I commited on the 19th. 2003-05-20 William Radcliffe * VisualMagick\configure : Fixed bug with add on (plug-ins) not building automatically in DLL mode. 2003-05-19 Bob Friesenhahn * magick/image.c (TextureImage): Creation of tiled image textures is speeded up by 3.7X. * coders/tile.c (ReadTILEImage): Use TextureImage. * VisualMagick/bin/modules.mgk: Map "PATTERN" to "LOGO". * coders/modules.mgk: Map "PATTERN" to "LOGO". * coders/logo.c (ReadLOGOImage): Add "PATTERN" tiling support in order to be compatible with ImageMagick. * magick/image.c (SetImageInfo): Map "MAGICK" magick to "IMAGE" in order to be compatible with ImageMagick. 2003-05-18 Bob Friesenhahn * www/Copyright.html: Try to fix formatting of XFig entry. * www/windows.html: Update file names for 1.0.1 release. * index.html: Mention 1.0.1 release as latest release. * magick/magick_config_api.h.in: Add define for HasX11 so that it is possible to use functions in the installed xwindow.h * */*.c: Updated to use MagickAllocateMemory macro. 2003-05-17 Glenn Randers-Pehrson * coders/png.c: stifled compiler warnings about uninitialized chunk and blob variables. 2003-05-17 Bob Friesenhahn * magick/utility.h (MagickAllocateMemory): New macro to allocate memory. (MagickFreeMemory): New macro to free memory. (MagickReallocMemory): New macro to reallocate memory. * */*.c,*/*.h: Updated to use MagickFreeMemory and MagickReallocMemory. Eliminated warnings when compiling with GCC 3.3 using -Wall. * images: The logo image was determined to have a copyright problem so replace with blank image until a replacement is available. 2003-05-16 Bob Friesenhahn * VisualMagick/magick/magick_config.h.in (HAVE_SYS_TYPES_H): Moved this define back from nt_base.h since removing it was causing some problems for Magick++. 2003-05-14 Bob Friesenhahn * magick/image.c: (SetMagickInfo): Don't mask failure to read magic.mgk. * magick/constitute.c (ReadImage): Don't overwrite specific exception info. * magick/nt_base.c (NTResourceToBlob): Add logging similar to that used in IsAccessible() in order to make operation more clear. * magick/module.c (FindMagickModule): Removed extraneous "Searching for module file" log event. (GetModuleBlob): Under Windows, don't clear or overwrite an existing exception. * magick/nt_base.h: Imported some obscure defines from magick\magick_config.h. * VisualMagick/magick/magick_config.h.in: Improved description text and formatting. Moved some obscure defines to magick/nt_base.h. * locale/C.mgk: Added a "RegistryKeyLookupFailed" error message. * magick/type.c (GetTypeBlob): Report registry key lookup failures. Also ensure correct return value when an error is reported. * magick/log.c (GetLogBlob): Report registry key lookup failures. * magick/delegate.c (ReadConfigureFile): Report registry key lookup failures. * magick/blob.c (GetConfigureBlob): Report registry key lookup failures. Also ensure correct return value when an error is reported. * magick/module.c (FindMagickModule): Report registry key lookup failures. Also ensure correct return value when an error is reported. * magick/nt_base.c (NTRegistryKeyLookup): Simplify base key lookup code, and improve coding style. * coders/logo.c, Copyright.txt, www/Copyright.html: Acknowledge and respect the XFig copyright. * VisualMagick/installer/inc/files-documentation.isx: QuickStart.txt is no longer distributed so it is removed. 2003-05-13 Bob Friesenhahn * magick/image.h (RoundToQuantum): New macro to round positive double to Quantum. * magick/xwindow.c, magick/xwindow.h, magick/studio.h: Use FreeBSD portability fixes from FreeBSD ports collection. * configure.ac: Test for as used by some *BSD systems. * QuickStart.txt, www/QuickStart.html: Don't distribute QuickStart.txt or www/QuickStart.html since the content doesn't currently apply to GraphicsMagick. 2003-05-12 Bob Friesenhahn * README.txt: Added text regarding where to obtain dcraw, a simple but useful decoder for the proprietary raw file formats produced by digital cameras (58 supported cameras!). * configure.ac: Added support for finding dcraw. * VisualMagick/bin/delegates.mgk: Added support for dcraw. * coders/delegates.mgk.in: Added support for dcraw. * version.sh (PACKAGE_RELEASE_DATE): Extract the most recent update date from the ChangeLog file using awk. 2003-05-12 William Radcliffe * modules.mgk, magic.mgk : Sync up both of these for UNIX as well as VisualMagick builds. Includes changes for the meta.c code. 2003-05-11 Bob Friesenhahn * www/formats.html: Documented embedded gray intensity images. * coders/logo.c: Added the embedded dithered gray intensity images gray0, gray5, ..., through gray100 to support bilevel filling and painting with an intensity resolution of 5%. * www/formats.html: Added description of images available via "IMAGE:" format tag, as well as providing a tiled preview. * coders/logo.c: Renamed "transparent" image to "checkerboard" since it is a better description. Added a set of tiny bilevel images (accessed via IMAGE:) for use when tiling, filling, or for use as a texture image. The complete set of image names available via the IMAGE: coder are now BRICKS, CIRCLES, CROSSHATCH, CROSSHATCH30, CROSSHATCH45, FISHSCALES, GRANITE, HEXAGONS, HORIZONTAL, HORIZONTALSAW, HS_BDIAGONAL, HS_CROSS, HS_DIAGCROSS, HS_FDIAGONAL, HS_HORIZONTAL, HS_VERTICAL, LEFT30, LEFT45, LEFTSHINGLE, LOGO, NETSCAPE, OCTAGONS, RIGHT30, RIGHT45, RIGHTSHINGLE, ROSE, SMALLFISHSCALES, CHECKERBOARD, VERTICAL, VERTICALBRICKS, VERTICALLEFTSHINGLE, VERTICALRIGHTSHINGLE, & VERTICALSAW. The HS_* variants are similar to the standard pattern images provided with the Windows GDI. * coders/msl.c (MSLStartElement): Don't reset gravity if the user provides an x,y coordinate. Passing coodinates was loosing the gravity setting. 2003-05-10 Bob Friesenhahn * coders/modules.mgk: Support the IMAGE: format via the LOGO module. * win2k/IMDisplay/IMDisplayView.cpp (DoDisplayImage): Transparent tile is created by reading "tile:image:transparent". * coders/logo.c (ReadLOGOImage): Add IMAGE: format to front for embedded images so that adding new images doesn't proliferate coder registrations. Legacy logo magick names (GRANITE, LOGO, NETSCAPE, and ROSE) are still supported, but they are also available in the IMAGE file space (e.g. IMAGE:ROSE). 2003-05-09 William Radcliffe * VisualMagick\configure : Further refinements that support both the new "big" library and the normal dynamic DLL buidling styles. 2003-05-09 Bob Friesenhahn * coders/logo.c (ReadLOGOImage): Added a "TRANSPARENT" pattern image which can be tiled to form the background of transparent images. * win32/IMDisplay/IMDisplayView.cpp: When displaying images which include an opacity channel, use a checker-board pattern as the image background so non-opaque pixels become evident. 2003-05-07 Bob Friesenhahn * coders/meta.c : Add or fix commenting of DebugString so that module does not require Windows. * lcms: Updated to release 1.10. 2003-05-07 William Radcliffe * VisualMagick\bin : Brought the MGK files back into sync with the rest of the package and added types for meta.c. * VisualMagick\bin\win32\ATL : removed config files in order to prevent very old ATL project from being picked up in the config 2003-05-06 William Radcliffe * VisualMagick\lcms\LIBRARY.txt : a define to prevent popup message box behaviour. * VisualMagick\configure\ : New feature - -t consolidates all the coders into on library for the static build in order to make the build process tolerable. * coders\xtrn.c : new support for BSTR - wdie character data * coders\svg.c : put back logic that allows the -size parameter to control the pixel dimensions of the output image. * coders\meta.c : added support for wide character parsing of iptc and 8BIM formats. 2003-05-06 Bob Friesenhahn * version.sh : Update to reflect development status. 2003-05-05 Bob Friesenhahn * GraphicsMagick 1.0 Released. * version.sh (LIBRARY_REVISION): Updated for the 1.0 release. * magick/studio.h: Add fix to avoid problems caused by zlib under AIX. * magick/cache.h: Parameterized prototypes to make them easier to follow. * filters/analyze.c: Replace C++ comments with C comments. * magick/command.c: For the composite, convert, identify, mogrify, and montage commands, make sure a usage error is returned if a usage message is printed. This is useful for ImageMagickObject users who won't see the usage message if stdio is not supported. * locale/C.mgk: Added "UsageError" error. Added missing closure to tag which caused most/many message lookups to fail. * magick/nt_base.h: Fixed a compile problem caused by masking internals in delegate.h * magick/ImageMagick.rc: Added missing .mgk files. 2003-05-04 Bob Friesenhahn * magick/nt_base.c (lt_dlerror): Defining lt_dlerror to be NTGetLastError was not a correct implementation since the interface is defined to return a const pointer to a string, but NTGetLastError returns an allocated string, causing a memory leak if NTGetLastError is used in the place of lt_dlerror. A new lt_dlerror function is added to fix this. (lt_dlsetsearchpath): lt_dlsetsearchpath should return an int and accept a const char *. (lt_dlsym): lt_dlsym is supposed to take a const char *. * magick/nt_base.h: lt_dlclose should return an `int`. * magick/nt_base.c (lt_dlclose): Return status from lt_dlclose. * magick/module.c (lt_dlclose): lt_dlclose is supposed to return an `int`, not `void`. A return value of zero indicates success. * VisualMagick/tests/run_constitute.bat: Add batch script to run constitute tests. * magick/module.c: Added a ltdl_initialized static flag to track if libltdl has been initialized by lt_dlinit(). (TagToFunctionName): Use a stack buffer for the string rather than allocating heap data. (UnregisterModule): Report errors via exception info as the interface suggests. (UnloadModule): Report errors via exception info as the interface suggests. (DestroyModuleInfo): Only invoke lt_dlexit() if lt_dlinit() has previously been invoked. * locale/C.mgk: Added FailedToCloseModule module error. * magick/module.c (UnloadModule): Report exception via exception parameter rather than simply printing out an error message and exiting. * magick/Makefile.am (noinst_HEADERS): integral_types.h had to be listed *somewhere* in order to make it into the distribution. * Magick++/lib/Magick++/Image.h: InitializeMagick must be DLL exported. 2003-05-03 Bob Friesenhahn * Makefile.am (magick-version): Perform version.isx substitutions via Makefile.am rather than configure. * magick/magick_config_api.h.in: Added template header for the installed magick_config.h. * magick/magick.c (InitializeMagick): Improved the signal handling and registration method. Signal handlers are only registered for a signal if the current signal handling disposition for that signal is set to the default (SIG_DFL). When a signal is caught, DestroyMagick is invoked, the handling for the signal is set back to SIG_DFL, and then the signal is re-raised to trigger the default handler for that signal. This causes the process to behave as closely to the default as possible (e.g. generating a core file) while ensuring that DestroyMagick is executed. This also ensures that signal handlers registered by API users are not overridden by invoking InitializeMagick. * configure.ac: Added tests for sigemptyset and sigaction. Add a check for the return type of signal handlers. Test for the `raise` function. * www/formats.html: Add an entry for CUR, Microsoft Cursor Icon format. 2003-05-02 Bob Friesenhahn * magick/semaphore.c (struct SemaphoreInfo): Added `locked` and `thread_id` members. These are used to record if the semaphore is locked, and to validate the thread ID of the unlocker. * www/links.html: Added link to Nathan Day's MagickDocs "ImageMagick and GraphicsMagick documentation project" site. Added a link to an on-line article regarding the PHP front-end to ImageMagick. * coders/icon.c (ReadIconImage): Add support for Windows .CUR format based on advice from Jean Piquemal. * magick/image.c (SetImageInfo): Added missing CloseBlob in error path for failure to allocate temporary file. * coders/pcx.c (ReadPCXImage): Added support for reading uncompressed PCX images based on code from Jean Piquemal. 2003-05-01 Bob Friesenhahn * magick/effect.c (AddNoiseImage): For gray images, wrong pointer was being used to evaluate intensity, leading to a black image with noise. * magick/image.c (ChannelImage): Return the channel image in RGBColorspace. Also properly support extracting the opacity channel for images which are not CMYK. 2003-04-30 Bob Friesenhahn * magick/Makefile.am (install-data-local): Install magick_config_api.h rather than magick_config.h. * magick/api.h: Removed inclusion of integral_types.h from magick/api.h. It is included by magick/studio.h. * magick/delegate.h: Mapped out a block of private implementation code. * configure.ac: Perform substitutions on magick_config_api.h. * magick/magick_config_api.h.in: New header file template to use for installed magick_config.h. * magick/studio.h (MAGICK_IMPLEMENTATION): Added the define MAGICK_IMPLEMENTATION used to enable private types, includes, and defines in the headers. This supports hiding implementation stuff that API users shouldn't see in the headers. * utilities/Makefile.am (check): Cleaned up the utilities test/demo a bit as well as using the undocumented "tmp:" prefix to cause GraphicsMagick to remove temporary input files once they have been read. This leaves just the final output file "demo.miff" when the test completes. * coders/jpeg.c (WriteJPEGImage): If the image resolution is overwritten with 72DPI, make sure that the resolution units are set to PixelsPerInchResolution. * coders/jpeg.c (WriteJPEGImage): Don't overwrite the image resolution if it is valid. * magick/command.c (MogrifyImageCommand): Added -resample option to match documentation. * VisualMagick/configure: Added rpcrt4.lib to project settings for Visual C++ 6.0 so that configure links. The code which needs these interfaces is to support Visual C++ 7.0 XML-style project files. 2003-04-30 Glenn Randers-Pehrson * utilities/Makefile.am (check) Change % to %% in -label parameter. * www/gm.html, utilities/gm.1, etc. Documented use of %% to convey the % sign in -format, -comment, -label strings. 2003-04-30 William Radcliffe * magick/command.c: Changes from 2003-04-19 to free the arg list when it was still pointed to by the option arg and accessed on an exception. This caused gm to crash on any erroneous command line argument. 2003-04-29 Bob Friesenhahn * www/windows.html: Updated to match current installer. * VisualMagick/installer/inc/tasks-install-devel.isx (Name): Added an installation checkbox so the user can select to install development headers and libraries for C & C++. * VisualMagick/installer/inc/files-perlmagick.isx (Source): Only install PerlMagick PPD files if the user selects to install PerlMagick. * VisualMagick/installer/inc/files-com.isx (Source): Only install ImageMagickObject files if the user selects to install ImageMagickObject. * magick/version.h.in: Added some documentation for the functioning of MagickLibVersion and MagickLibVersionNumber. * configure.ac: Perform substutions to create VisualMagick/installer/inc/version.isx from VisualMagick/installer/inc/version.isx.in. This allows Windows versioning info to be updated from info in version.sh. * Makefile.am (magick-version): For a VPATH build, update VisualMagick/installer/inc/version.isx in the source directory if it is out of date. 2003-04-28 Glenn Randers-Pehrson * magick/cache.c: CloneImagePixels(): applied Cristy's bugfix from IM-5.5.7. 2003-04-28 Bob Friesenhahn * www/api.html: The demo program on the ImageMagick API page is usually intended to be an exercise for the reader. It rarely compiles or works. Sure enough the demo code was not even close to compiling, didn't run, and did something totally different than described. This is not a good way to treat new users. Now the demo program compiles and runs, and its description is correct. * www/magick.css, www/smile.c: Remove "Pair" advertisement which was discovered appended at the end of these files. * coders/jpeg.c (ReadJPEGImage): Check for failure of AllocateImage. Close blob prior to error return. * configure.ac: Perform substitutions on magick/version.h * magick/version.h.in: New file to provide base for configured magick/version.h * version.sh (PACKAGE_RELEASE_DATE): Support setting a package release date. * configure.ac: Perform substitutions on PerlMagick/Magick.pm.in to create PerlMagick/Magick.pm.in. * PerlMagick/Magick.pm.in: @PACKAGE_VERSION@ is substituted while configuring PerlMagick/Magick.pm. * magick/magic.mgk, VisualMagick/bin/magic.mgk: Removed risky entry for PICT which has been demonstrated to lead to a false match in the real-world. * coders/pict.c (ReadPICTImage): Ensure that PICT decoder don't loop forever with an EOF condition if none of the PICT op-codes encountered result in a condition which terminates the input loop. If EOF is dectected while in the input loop a "corrupt image" "unexpected end of file" error is reported. * VisualMagick/installer: Updated installer. 2003-04-26 Bob Friesenhahn * magick/magick.c, magick/blob.c, magick/studio.h: Added Compilation fixes recommended by Harold Bien for for Borland C++. * www/contribute.html: Added text regarding contributing to GraphicsMagick. * www/api/types.html: Documentation for GraphicsMagick API types moved from www/api/types/*.html into this one file. Types documentation is still very much under development. * README.txt: Added note regarding the download location for free Windows fonts which are kindly made available by Microsoft. * VisualMagick/installer/gm-dynamic-full-*.iss: Install nt_base.h and nt_feature.h. 2003-04-24 Bob Friesenhahn * www/windows.html: Updated for GraphicsMagick 1.0 and to link to ImageMagickObject.html. * www/programming.html: Added link to ImageMagickObject.html. * www/ImageMagickObject.html: New file to provide some documentation for ImageMagickObject. * www: Found and fixed broken URL links. 2003-04-23 Bob Friesenhahn * FlashPIX: Applied patches from FreeBSD. Bumped package version to version to 1.2.0.8. * www/api.html: Updated to reflect GraphicsMagick * www/*.html: Updated with format_c_api_docs script. * Makefile.am (format_c_api_docs): Add a target to update the C API documentation. * scripts/format_c_api_docs: Add script which extracts and formats the C API documentation into HTML files in the www/api subdirectory. 2003-04-22 Bob Friesenhahn * version.sh (PACKAGE_VERSION): Update release version ID. * magick/version.h (MagickReleaseDate): Update release date. * magick/constitute.c (ConstituteImage): Fixed problems with reading intensity (gray) pixel arrays. * magick/image.c (GrayscalePseudoClassImage): Use ScaleQuantumToIndex rather than ScaleQuantumToMap. * magick/constitute.c (ConstituteImage): Use ScaleQuantumToIndex macro to scale integral intensity values to colormap range. * magick/image.h (ScaleQuantumToIndex): New macro to scale a quantum to the maximum range of a colormap index. Useful when writing to PsuedoClass grayscale images. * VisualMagick/tests/run_constitute.bat: Batch script to run constitute tests. * VisualMagick/installer/*.iss: Updated for Beta1 release. 2003-04-22 Glenn Randers-Pehrson * utilities/Makefile.am (check) fixed typos (RM -> RMDelegate and removed stray "gm"), added -random-threshold, ordered-dither. * magick/effect.c: Random-threshold was not treating non-gray PseudoColor images correctly. 2003-04-21 Bob Friesenhahn * utilities/Makefile.am (check): Added code to put logo on demo output. * magick/command.c (MontageImageCommand): Pass exception rather than &image->exception because image may be null, and it is pointless to store the exception where it will not be reported to the user anyway. * utilities/Makefile.am (check): Ported Glenn Randers-Pehrson's utilities demo script into the Makefile to serve as a check target. (check): Add definition to find Generic.ttf. * locale/C.mgk: Fixed syntax error in