Compare commits

...

44 Commits

Author SHA1 Message Date
502d158bc0 fix: version 2.9.2 (#4405) 2025-09-01 15:33:50 +08:00
f08897a114 chore(tablewriter): upgrade to v1.0.9 and refactor table rendering logic (#4352)
### What’s Changed

* Upgraded `github.com/olekukonko/tablewriter` from previous version to
**v1.0.9**.

---------

Co-authored-by: hailaz <739476267@qq.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-09-01 12:20:22 +08:00
b6181e4bde fix: report coverage on the latest go version (#4398) 2025-08-29 16:10:37 +08:00
613
f8cdeae2d7 fix(net/goai): fix g.Meta is passed as parameters of a request (#4397)
fix https://github.com/gogf/gf/issues/4247

<img width="2860" height="2308" alt="image"
src="https://github.com/user-attachments/assets/755cfe8a-b3ae-4c5a-ba04-68cc1b188ca7"
/>
2025-08-29 15:30:28 +08:00
bea060af4c feat: update linter config and deprecation notice (#4399)
- Add `gofmt` rewrite-rules to `.golangci.yml` for code formatting
consistency.
- Update deprecation comment in `gpage.go` to specify removal in version
3.0.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-29 15:26:56 +08:00
94cc233325 fix: disable specific staticcheck rules and update lint config (#4396)
fix: disable specific staticcheck rules and update lint config

- Disabled staticcheck rules SA1029, SA1019, S1000, and related checks
in `.golangci.yml` to filter out unwanted linter errors.
- Updated staticcheck checks list for more precise linting control.
- Clarified configuration for easier maintenance and future updates.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: hailaz <739476267@qq.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-29 10:32:30 +08:00
fsl
71743e6903 chore: add OpenSSF Scorecard for README.md (#3696)
Why is this needed:

The OpenSSF Scorecard improves open-source project's security by
providing automated, transparent assessments of their security
practices. It will help you identify vulnerabilities, adhere to best
practices, and continuously enhance your security posture, increasing
user trust and reducing the risk of security exploits.

I'll be the one to create the PR to add the scorecard GitHub action, and
I will also work with you to remediate the identified vulnerabilities.
I'll go through each [scorecard
check](https://github.com/ossf/scorecard/blob/main/docs/checks.md) to
see where the score has dropped and how it can be improved.


Integrate [scorecard](https://github.com/ossf/scorecard) in CI, and
display a Scorecard badge on the gogf repository
You also need to manually create a project, refer to
https://bestpractices.coreinfrastructure.org/en/projects
Manually create an gogf organization to report results, please see
https://sonarcloud.io/explore/projects?sort=-analysis_date

Signed-off-by: fsl <1171313930@qq.com>
2025-08-29 10:28:29 +08:00
f9ec3b19f7 fix(net/ghttp): wrong in-tag param parse for query param (#4227) (#4228)
Fixed issue #4227 and add unit test

---------

Co-authored-by: hailaz <739476267@qq.com>
2025-08-29 09:46:48 +08:00
ee24da4e72 refactor: interface{} to any and reflect.Ptr to reflect.Pointer (#4395)
This pull request standardizes the use of the Go 1.18+ `any` type alias
instead of `interface{}` throughout the codebase. The change improves
code readability and aligns with modern Go best practices. The update
touches many files, including core data structures, code generation
templates, logging utilities, and test data, ensuring consistency across
all usages.

**Type alias migration to `any`:**

* Replaced all instances of `interface{}` with `any` in core data
structures such as `garray` and in generated model structs (e.g.,
`TableUser`, `User1`, `User2`) to modernize type usage.
[[1]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L31-R31)
[[2]](diffhunk://#diff-6c19859cb32c7516ea95ddc8f8235460818eb2f24d2204308e0d9e1b19e7d90fL15-R19)
[[3]](diffhunk://#diff-a15ba2f5e830b4833c47b902515a4f9e5a4f83a3707698f3229b307ec3776b41L15-R18)
[[4]](diffhunk://#diff-52e0837e84d49221d1b810d88fdf78221f36cffcd664fb42f8aba49a79b974dcL15-R19)
[[5]](diffhunk://#diff-11c3457d1a23a4ca6ecd00d6b856289774936b6a708384cf03aff164044e7546L15-R19)
[[6]](diffhunk://#diff-2cff9cf8e6a0cc34087326d8c8149c3bbaf74c76fdbdf5a73daed13cc04249e1L15-R19)
* Updated function signatures, method parameters, and return types from
`interface{}` to `any` in various parts of the codebase, including code
generation, service logic, and logging utilities (e.g., `mlog`).
[[1]](diffhunk://#diff-175edfeea54490b8fe4e18ffcbea5835efaf8f0b8acf623359073987cae7eb76L48-R55)
[[2]](diffhunk://#diff-2b1953fb78cf3593d8c2c7d911e95b65fd0b847c30ed0b4d167d16fe6d781235L54-R74)
[[3]](diffhunk://#diff-e001b7a4b63603b9b14f00de78a4d570bb76c5f57d856a24643f071032e12356L66-R73)
[[4]](diffhunk://#diff-5582954e8a9983988dc8854ad82067fb2ac6269b988e07357ad8db1dfec5f1a0L39-R41)
[[5]](diffhunk://#diff-c5d51d56f487779a2b6207c7ad26c7a20bbadcc846ce094fe60ab4cabff58c51L107-R107)
[[6]](diffhunk://#diff-f96e6a9fdb416eb1804ceaba1fe0ac637bff22c43837f8bb849c2366ce72d4a1L116-R121)
[[7]](diffhunk://#diff-f94c83a1b08ae060d9346f4a6031fc4a7b9a0b894e02d9afaa09018b6598eac0L112-R112)
[[8]](diffhunk://#diff-748b11dbe8828dd4c040ec23cae0b8fe57ecf0a2d1b7694ea39102294e633c64L36-R36)
[[9]](diffhunk://#diff-748b11dbe8828dd4c040ec23cae0b8fe57ecf0a2d1b7694ea39102294e633c64L74-R74)
[[10]](diffhunk://#diff-748b11dbe8828dd4c040ec23cae0b8fe57ecf0a2d1b7694ea39102294e633c64L96-R96)

**Generated code and templates:**

* Adjusted generated files and code generation templates to output `any`
instead of `interface{}` for relevant struct fields and function
signatures, ensuring that new code generation aligns with the updated
convention.
[[1]](diffhunk://#diff-6c19859cb32c7516ea95ddc8f8235460818eb2f24d2204308e0d9e1b19e7d90fL15-R19)
[[2]](diffhunk://#diff-a15ba2f5e830b4833c47b902515a4f9e5a4f83a3707698f3229b307ec3776b41L15-R18)
[[3]](diffhunk://#diff-52e0837e84d49221d1b810d88fdf78221f36cffcd664fb42f8aba49a79b974dcL15-R19)
[[4]](diffhunk://#diff-11c3457d1a23a4ca6ecd00d6b856289774936b6a708384cf03aff164044e7546L15-R19)
[[5]](diffhunk://#diff-2cff9cf8e6a0cc34087326d8c8149c3bbaf74c76fdbdf5a73daed13cc04249e1L15-R19)
[[6]](diffhunk://#diff-175edfeea54490b8fe4e18ffcbea5835efaf8f0b8acf623359073987cae7eb76L48-R55)
[[7]](diffhunk://#diff-e001b7a4b63603b9b14f00de78a4d570bb76c5f57d856a24643f071032e12356L66-R73)
[[8]](diffhunk://#diff-5582954e8a9983988dc8854ad82067fb2ac6269b988e07357ad8db1dfec5f1a0L39-R41)

**Container and utility updates:**

* Refactored the `garray` container implementation and related
constructors/methods to use `[]any` instead of `[]interface{}`, along
with corresponding function signatures.
[[1]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L31-R31)
[[2]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L52-R52)
[[3]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L62-R62)
[[4]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L73-R86)
[[5]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L96-R97)
[[6]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L107-R114)
[[7]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L124-R124)
[[8]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L135-R143)
[[9]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L167-R167)

These changes collectively modernize the codebase and prepare it for
future Go developments by using the idiomatic `any` type.
2025-08-28 16:53:19 +08:00
26f20787ba perf(net/gclient): optimize default http.Transport connection pool configuration (#4390) 2025-08-28 15:08:25 +08:00
1371b3bad5 fix: revert #4388 (#4392) 2025-08-28 13:00:08 +08:00
1da73451b9 fix: spacing in min value validation message (#4388)
Fix spacing in min value validation message
2025-08-27 19:05:55 +08:00
94b623e126 fix: update dependencies to version v2.9.1 for various contrib modules and drivers (#4386)
Fixes #4385
2025-08-27 12:21:38 +08:00
4262aa254d chore(deps): Update dependent versions to enhance compatibility and security (#4380)
#4344

---------

Co-authored-by: houseme <housemecn@gmail.com>
2025-08-23 14:53:49 +08:00
8cff64915b fix(tracing): set database span kind to client (#4334)
In [OpenTelemetry
spec](https://opentelemetry.io/docs/specs/semconv/database/database-spans/),
the span kind of database should be `client`.
2025-08-22 22:49:13 +08:00
bec98e8de0 fix(database/gdb): clickhouse can not support int128/int256/uint128/uint256 (#4370)
When use clickhouse and use field type int128/int256/uint128/uint256. It
can not work well and it will return 0 value.
Add the new field types to let it work well.

By the way, the data struct field need be set to big.Int when use the
types.
2025-08-22 22:05:15 +08:00
a6dbf4b7eb feat: upgrade workflow checkout version v5 (#4381)
feat: upgrade workflow checkout version v5

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-22 21:58:00 +08:00
0c2f60468b chore(deps): bump github.com/redis/go-redis/v9 from 9.7.0 to 9.12.1 in /contrib/nosql/redis (#4215)
Bumps [github.com/redis/go-redis/v9](https://github.com/redis/go-redis)
from 9.7.0 to 9.7.3.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/redis/go-redis/releases">github.com/redis/go-redis/v9's
releases</a>.</em></p>
<blockquote>
<h2>v9.7.3</h2>
<h2>What's Changed</h2>
<ul>
<li>fix: handle network error on SETINFO (<a
href="https://redirect.github.com/redis/go-redis/issues/3295">#3295</a>)
(<a
href="https://github.com/redis/go-redis/security/advisories/GHSA-92cp-5422-2mw7">CVE-2025-29923</a>)</li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/redis/go-redis/compare/v9.7.1...v9.7.3">https://github.com/redis/go-redis/compare/v9.7.1...v9.7.3</a></p>
<h2>v9.7.1</h2>
<h1>Changes</h1>
<ul>
<li>Recognize byte slice for key argument in cluster client hash slot
computation (<a
href="https://redirect.github.com/redis/go-redis/issues/3049">#3049</a>)</li>
<li>fix(search&amp;aggregate):fix error overwrite and typo <a
href="https://redirect.github.com/redis/go-redis/issues/3220">#3220</a>
(<a
href="https://redirect.github.com/redis/go-redis/issues/3224">#3224</a>)</li>
<li>fix: linter configuration (<a
href="https://redirect.github.com/redis/go-redis/issues/3279">#3279</a>)</li>
<li>fix(search): if ft.aggregate use limit when limitoffset is zero (<a
href="https://redirect.github.com/redis/go-redis/issues/3275">#3275</a>)</li>
<li>Reinstate read-only lock on hooks access in dialHook to fix data
race (<a
href="https://redirect.github.com/redis/go-redis/issues/3225">#3225</a>)</li>
<li>fix: flaky ClientKillByFilter test (<a
href="https://redirect.github.com/redis/go-redis/issues/3268">#3268</a>)</li>
<li>chore: fix some comments (<a
href="https://redirect.github.com/redis/go-redis/issues/3226">#3226</a>)</li>
<li>fix(aggregate, search): ft.aggregate bugfixes (<a
href="https://redirect.github.com/redis/go-redis/issues/3263">#3263</a>)</li>
<li>fix: add unstableresp3 to cluster client (<a
href="https://redirect.github.com/redis/go-redis/issues/3266">#3266</a>)</li>
<li>Fix race condition in clusterNodes.Addrs() (<a
href="https://redirect.github.com/redis/go-redis/issues/3219">#3219</a>)</li>
<li>SortByWithCount FTSearchOptions fix (<a
href="https://redirect.github.com/redis/go-redis/issues/3201">#3201</a>)</li>
<li>Eliminate redundant dial mutex causing unbounded connection queue
contention (<a
href="https://redirect.github.com/redis/go-redis/issues/3088">#3088</a>)</li>
<li>Add guidance on unstable RESP3 support for RediSearch commands to
README (<a
href="https://redirect.github.com/redis/go-redis/issues/3177">#3177</a>)</li>
</ul>
<h2>🚀 New Features</h2>
<ul>
<li>Add guidance on unstable RESP3 support for RediSearch commands to
README (<a
href="https://redirect.github.com/redis/go-redis/issues/3177">#3177</a>)</li>
</ul>
<h2>🐛 Bug Fixes</h2>
<ul>
<li>fix(search): if ft.aggregate use limit when limitoffset is zero (<a
href="https://redirect.github.com/redis/go-redis/issues/3275">#3275</a>)</li>
<li>fix: add unstableresp3 to cluster client (<a
href="https://redirect.github.com/redis/go-redis/issues/3266">#3266</a>)</li>
<li>fix(aggregate, search): ft.aggregate bugfixes (<a
href="https://redirect.github.com/redis/go-redis/issues/3263">#3263</a>)</li>
<li>SortByWithCount FTSearchOptions fix (<a
href="https://redirect.github.com/redis/go-redis/issues/3201">#3201</a>)</li>
<li>Recognize byte slice for key argument in cluster client hash slot
computation (<a
href="https://redirect.github.com/redis/go-redis/issues/3049">#3049</a>)</li>
</ul>
<h2>Contributors</h2>
<p>We'd like to thank all the contributors who worked on this
release!</p>
<p><a
href="https://github.com/ofekshenawa"><code>@​ofekshenawa</code></a>, <a
href="https://github.com/Cgol9"><code>@​Cgol9</code></a>, <a
href="https://github.com/LINKIWI"><code>@​LINKIWI</code></a>, <a
href="https://github.com/shawnwgit"><code>@​shawnwgit</code></a>, <a
href="https://github.com/zhuhaicity"><code>@​zhuhaicity</code></a>, <a
href="https://github.com/bitsark"><code>@​bitsark</code></a>, <a
href="https://github.com/vladvildanov"><code>@​vladvildanov</code></a>,
<a href="https://github.com/ndyakov"><code>@​ndyakov</code></a></p>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/redis/go-redis/compare/v9.7.0...v9.7.1">https://github.com/redis/go-redis/compare/v9.7.0...v9.7.1</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="a29d91d9ca"><code>a29d91d</code></a>
release 9.7.3, retract 9.7.2 (<a
href="https://redirect.github.com/redis/go-redis/issues/3314">#3314</a>)</li>
<li><a
href="ce3034c7b3"><code>ce3034c</code></a>
bump version to 9.7.2</li>
<li><a
href="0af2b32f93"><code>0af2b32</code></a>
fix: handle network error on SETINFO (<a
href="https://redirect.github.com/redis/go-redis/issues/3295">#3295</a>)
(CVE-2025-29923)</li>
<li><a
href="3d041a1dd6"><code>3d041a1</code></a>
release: 9.7.1 patch (<a
href="https://redirect.github.com/redis/go-redis/issues/3278">#3278</a>)</li>
<li>See full diff in <a
href="https://github.com/redis/go-redis/compare/v9.7.0...v9.7.3">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=github.com/redis/go-redis/v9&package-manager=go_modules&previous-version=9.7.0&new-version=9.7.3)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts page](https://github.com/gogf/gf/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-22 17:11:09 +08:00
656ae070da fix(cmd/gf): fix gen sharding dao in multiple shardingPattern tables … (#4379)
fix #4378 
fix #4330

---------

Co-authored-by: hailaz <739476267@qq.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-22 16:46:23 +08:00
2d5fcd73cb chore: upgrade dependencies to latest versions and fix security vulne… (#4237)
This PR includes the following updates and fixes:

- **Dependency upgrades**: Updated all dependencies in `go.mod` to their
latest versions to ensure compatibility and leverage the latest features
and fixes.
- **Security fixes**:
- Resolved known vulnerabilities in `golang.org/x/net` by upgrading to
the latest secure version.
- Addressed security issues in `golang.org/x/crypto` by upgrading to the
latest secure version.

These changes improve the overall security and stability of the project.
Please review the changes and ensure compatibility with the updated
dependencies.

---------

Co-authored-by: hailaz <739476267@qq.com>
2025-08-22 15:29:16 +08:00
82043856f4 chore(polaris): Bump github.com/polarismesh/polaris-go from v1.5.8 to v1.6.1 (#4241)
- Updated `github.com/polarismesh/polaris-go` dependency to v1.6.1 in
`go.mod`.
- Ensured compatibility with the latest changes in the Polaris Go SDK.
- Verified that all related functionality works as expected after the
upgrade.
- Resolved any potential breaking changes introduced in the new version.

This upgrade includes performance improvements, bug fixes, and new
features provided by the Polaris Go SDK.
2025-08-22 15:07:34 +08:00
7ffdff37e4 chore: upgrade golangci-lint configuration and optimize codebase (#4236)
This PR includes the following changes:

- **Upgrade `.golangci.yml`**: Updated the configuration file to align
with the latest golangci-lint version, ensuring compatibility and
leveraging new features.
- **Refactor GitHub Action workflow**: Modified `golangci-lint.yml` in
the GitHub Actions workflow to reflect the updated configuration and
improve CI performance.
- **Codebase optimization**: Refactored code to address issues and
warnings raised by the updated golangci-lint rules, including:
  - Improved function length and complexity.
  - Enhanced error handling and variable naming conventions.
- Fixed minor issues such as unused imports and formatting
inconsistencies.

These changes aim to maintain code quality, ensure compatibility with
the latest tools, and improve overall maintainability.
2025-08-22 13:29:09 +08:00
613
24083b865d fix(internal/utils): fix +.1 is pass checks numeric (#4374) 2025-08-21 15:44:26 +08:00
8cb64c9f88 fix(cmd/gf): "unknown time zone" when using "gf gen dao" for clickhouse on windows platform (#4368)
fix bug: could not load time location: "unknown time zone Asia/Shanghai"

The bug will appear when I use gf in windows to do "gf gen dao" for
clickhouse.
2025-08-15 13:35:59 +08:00
5fa656d1cc fix(os/gtime): add handling for nil time pointers to avoid causing panic (#4323)
from https://github.com/gogf/gf/pull/4322
Fixes https://github.com/gogf/gf/issues/4307
2025-06-24 15:53:47 +08:00
09ec90746a chore: bump golang.org/x/tools to v0.34.0 for Go 1.25 compatibility (#4313)
chore: bump golang.org/x/tools to v0.34.0 for Go 1.25 compatibility

```
   # golang.org/x/tools/internal/tokeninternal
  /Users/brew/Library/Caches/Homebrew/go_mod_cache/pkg/mod/golang.org/x/tools@v0.21.1-0.20240508182429-e35e4ccd0d2d/internal/tokeninternal/tokeninternal.go:64:9: invalid array length -delta * delta (constant -256 of type int64)
```

relates to https://github.com/Homebrew/homebrew-core/pull/226636
2025-06-20 21:21:03 +08:00
c0d1e44526 fix(database/gdb): support multiple order fields in gdb_model_with and merged #4272 fix scanning functionality for deep slice types (#4320)
Fix:#4311
Merged: #4272
2025-06-20 21:09:41 +08:00
b323862b4c Merge pull request #1 from fainc/master
Update util/gconv/gconv_z_unit_scan_test.go
2025-06-20 19:23:04 +08:00
3d9cdb8997 fix(gdb): support multiple order fields in "with" 2025-06-20 19:11:01 +08:00
7180d895ea Update util/gconv/gconv_z_unit_scan_test.go
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-06-20 18:17:40 +08:00
afb1595fbe Merge branch 'gogf:master' into master 2025-06-20 18:07:15 +08:00
6637add9ca fix(net/ghttp): improve GetMetaTag method to handle nil and type checks (#4284)
修复没有做handler参数数量判断导致可能出现的数组越界问题
2025-06-19 09:43:24 +08:00
bc862cf97b chore: bump golang.org/x/tools to v0.34.0 for Go 1.25 compatibility
Signed-off-by: Rui Chen <rui@chenrui.dev>
2025-06-14 13:34:25 -04:00
9033ca087b fix(net/ghttp): improve GetMetaTag method to handle nil and type checks 2025-05-16 17:55:00 +08:00
b985fd978c Merge branch 'master' into master 2025-05-07 20:02:12 +08:00
88c4471500 fix(ci): change base image from expired ubuntu-22.04 to ubuntu-latest (#4273) 2025-05-07 19:06:00 +08:00
b73e2047db fix(gconv): fix scanning functionality for deep slice types 2025-05-06 13:37:45 +08:00
1534abdb05 feat(util/gpage): marked deprecated (#4230) 2025-04-02 19:56:28 +08:00
fee38b4531 feat(net/ghttp): enhance GetHeader method to support default values (#4210) 2025-03-25 20:42:30 +08:00
69e3362d0d feat: new version v2.9.0 (#4204) 2025-03-17 15:52:26 +08:00
9a61a6970f fix(database/gdb): fix transaction propagation feature (#4199) 2025-03-17 14:50:07 +08:00
abf77fac50 fix(cmd/gf): invalid binary suffix after installing binary using custom renamed file name that has suffix with . character (#4207) 2025-03-17 13:48:54 +08:00
07696fc779 feat(net/ghttp): add GetMetaTag function to retrieve metadata value for HandlerItem (#4206) 2025-03-17 09:21:00 +08:00
bc1e1019c5 refract(util/gconv): change Converter interface definition for more convenient usage (#4202) 2025-03-14 18:23:07 +08:00
699 changed files with 8100 additions and 7328 deletions

View File

@ -29,7 +29,7 @@ concurrency:
env: env:
TZ: "Asia/Shanghai" TZ: "Asia/Shanghai"
# for unit testing cases of some components that only execute on the latest go version. # for unit testing cases of some components that only execute on the latest go version.
LATEST_GO_VERSION: "1.23" LATEST_GO_VERSION: "1.25"
jobs: jobs:
code-test: code-test:
@ -38,12 +38,11 @@ jobs:
# 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥 # 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
# When adding new go version to the list, make sure: # When adding new go version to the list, make sure:
# 1. Update the `LATEST_GO_VERSION` env variable. # 1. Update the `LATEST_GO_VERSION` env variable.
# 2. Update the `Report Coverage` action.
# 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥 # 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
go-version: [ "1.22", "1.23" ] go-version: [ "1.23", "1.24", "1.25" ]
goarch: [ "386", "amd64" ] goarch: [ "386", "amd64" ]
runs-on: ubuntu-20.04 runs-on: ubuntu-latest
# Service containers to run with `code-test` # Service containers to run with `code-test`
services: services:
@ -206,7 +205,7 @@ jobs:
timezoneLinux: "Asia/Shanghai" timezoneLinux: "Asia/Shanghai"
- name: Checkout Repository - name: Checkout Repository
uses: actions/checkout@v4 uses: actions/checkout@v5
- name: Start Apollo Containers - name: Start Apollo Containers
run: docker compose -f ".github/workflows/apollo/docker-compose.yml" up -d --build run: docker compose -f ".github/workflows/apollo/docker-compose.yml" up -d --build
@ -227,9 +226,9 @@ jobs:
cache-dependency-path: '**/go.sum' cache-dependency-path: '**/go.sum'
- name: Install Protoc - name: Install Protoc
uses: arduino/setup-protoc@v2 uses: arduino/setup-protoc@v3
with: with:
version: "29.x" version: "31.x"
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}
- name: Install the protocol compiler plugins for Go - name: Install the protocol compiler plugins for Go
@ -263,8 +262,8 @@ jobs:
- name: Report Coverage - name: Report Coverage
uses: codecov/codecov-action@v4 uses: codecov/codecov-action@v4
# Only report coverage on the latest go version and amd64 arch # Only report coverage on the latest go version
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && matrix.go-version == '1.23' && matrix.goarch == 'amd64' }} if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && matrix.go-version == env.LATEST_GO_VERSION }}
with: with:
flags: go-${{ matrix.go-version }}-${{ matrix.goarch }} flags: go-${{ matrix.go-version }}-${{ matrix.goarch }}
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}

View File

@ -30,7 +30,7 @@ concurrency:
env: env:
TZ: "Asia/Shanghai" TZ: "Asia/Shanghai"
# for unit testing cases of some components that only execute on the latest go version. # for unit testing cases of some components that only execute on the latest go version.
LATEST_GO_VERSION: "1.23" LATEST_GO_VERSION: "1.25"
jobs: jobs:
code-test: code-test:
@ -40,7 +40,7 @@ jobs:
# When adding new go version to the list, make sure: # When adding new go version to the list, make sure:
# 1. Update the `LATEST_GO_VERSION` env variable. # 1. Update the `LATEST_GO_VERSION` env variable.
# 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥 # 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
go-version: [ "1.22", "1.23" ] go-version: [ "1.23", "1.24", "1.25" ]
goarch: [ "386", "amd64" ] goarch: [ "386", "amd64" ]
runs-on: ubuntu-latest runs-on: ubuntu-latest
@ -52,7 +52,7 @@ jobs:
timezoneLinux: "Asia/Shanghai" timezoneLinux: "Asia/Shanghai"
- name: Checkout Repository - name: Checkout Repository
uses: actions/checkout@v4 uses: actions/checkout@v5
- name: Start Minikube - name: Start Minikube
uses: medyagh/setup-minikube@master uses: medyagh/setup-minikube@master

View File

@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v5
- name: Setup Golang ${{ matrix.go-version }} - name: Setup Golang ${{ matrix.go-version }}
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:

View File

@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout source code - name: Checkout source code
uses: actions/checkout@v4 uses: actions/checkout@v5
- name: Mirror GitHub to Gitee - name: Mirror GitHub to Gitee
uses: Yikun/hub-mirror-action@v1.4 uses: Yikun/hub-mirror-action@v1.4
with: with:

View File

@ -4,7 +4,7 @@
# If a copy of the MIT was not distributed with this file, # If a copy of the MIT was not distributed with this file,
# You can obtain one at https://github.com/gogf/gf. # You can obtain one at https://github.com/gogf/gf.
name: GolangCI Lint name: golangci-lint
on: on:
push: push:
branches: branches:
@ -29,23 +29,24 @@ jobs:
golang-ci: golang-ci:
strategy: strategy:
matrix: matrix:
go-version: [ 'stable' ] go-version: [ "stable" ]
name: golang-ci-lint name: golang-ci-lint
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup Golang ${{ matrix.go-version }} - name: Setup Golang ${{ matrix.go-version }}
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: ${{ matrix.go-version }} go-version: ${{ matrix.go-version }}
- name: golang-ci-lint - name: golang-ci-lint
uses: golangci/golangci-lint-action@v6 uses: golangci/golangci-lint-action@v8
with: with:
# Required: specify the golangci-lint version without the patch version to always use the latest patch. # Required: specify the golangci-lint version without the patch version to always use the latest patch.
version: v1.64.5
only-new-issues: true only-new-issues: true
skip-cache: true skip-cache: true
github-token: ${{ secrets.GITHUB_TOKEN }} github-token: ${{ secrets.GITHUB_TOKEN }}
args: --timeout 3m0s --config=.golangci.yml -v args: --config=.golangci.yml -v

View File

@ -23,6 +23,6 @@ jobs:
with: with:
actions: 'check-inactive' actions: 'check-inactive'
inactive-label: 'inactive' inactive-label: 'inactive'
inactive-day: 7 inactive-day: 30
issue-state: open issue-state: open
exclude-labels: 'bug,planned,$exclude-empty' exclude-labels: 'bug,planned,$exclude-empty'

View File

@ -16,12 +16,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Github Code - name: Checkout Github Code
uses: actions/checkout@v4 uses: actions/checkout@v5
- name: Set Up Golang Environment - name: Set Up Golang Environment
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: 1.23.4 go-version: 1.25
- name: Build CLI Binary - name: Build CLI Binary
run: | run: |

View File

@ -19,7 +19,7 @@ for file in `find . -name go.mod`; do
continue 1 continue 1
fi fi
# package kuhecm was moved to sub ci procedure. # package kubecm was moved to sub ci procedure.
if [ "kubecm" = $(basename $dirpath) ]; then if [ "kubecm" = $(basename $dirpath) ]; then
continue 1 continue 1
fi fi

View File

@ -2,26 +2,67 @@
coverage=$1 coverage=$1
# Function to compare version numbers
version_compare() {
local ver1=$1
local ver2=$2
# Remove 'go' prefix and 'v' if present
ver1=$(echo "$ver1" | sed 's/^go//; s/^v//')
ver2=$(echo "$ver2" | sed 's/^go//; s/^v//')
# Split versions into major.minor format
local major1=$(echo "$ver1" | cut -d. -f1)
local minor1=$(echo "$ver1" | cut -d. -f2)
local major2=$(echo "$ver2" | cut -d. -f1)
local minor2=$(echo "$ver2" | cut -d. -f2)
# Compare versions: return 0 if ver1 <= ver2, 1 otherwise
if [ "$major1" -lt "$major2" ]; then
return 0
elif [ "$major1" -eq "$major2" ] && [ "$minor1" -le "$minor2" ]; then
return 0
else
return 1
fi
}
# Get current Go version
current_go_version=$(go version | grep -oE 'go[0-9]+\.[0-9]+')
# find all path that contains go.mod. # find all path that contains go.mod.
for file in `find . -name go.mod`; do for file in `find . -name go.mod`; do
dirpath=$(dirname $file) dirpath=$(dirname $file)
echo $dirpath echo "Processing: $dirpath"
# package kuhecm needs golang >= v1.19 # Only process kubecm directory, skip others
if [ "kubecm" = $(basename $dirpath) ]; then if [ "kubecm" != $(basename $dirpath) ]; then
if ! go version|grep -qE "go1.[2-9][0-9]"; then echo " Skipping: not kubecm directory"
echo "ignore kubecm as go version: $(go version)" continue
continue 1
fi
else
continue 1
fi fi
cd $dirpath cd $dirpath
go mod tidy # Read Go version requirement from go.mod
go build ./... if [ -f "go.mod" ]; then
go test ./... -race || exit 1 go_mod_version=$(grep '^go ' go.mod | awk '{print $2}' | head -1)
if [ -n "$go_mod_version" ]; then
echo " go.mod requires: go$go_mod_version"
echo " current version: $current_go_version"
# Check if go.mod version requirement is satisfied by current Go version
if version_compare "$go_mod_version" "$current_go_version"; then
echo " ✓ Version requirement satisfied, proceeding with build and test"
go mod tidy
go build ./...
go test ./... -race || exit 1
else
echo " ✗ Current Go version ($current_go_version) does not meet requirement (go$go_mod_version), skipping"
fi
fi
fi
cd - cd -
done done

View File

@ -17,7 +17,7 @@ permissions: read
jobs: jobs:
analysis: analysis:
name: Scorecards analysis name: Scorecards analysis
runs-on: ubuntu-22.04 runs-on: ubuntu-latest
permissions: permissions:
# Needed to upload the results to code-scanning dashboard. # Needed to upload the results to code-scanning dashboard.
security-events: write security-events: write
@ -29,7 +29,7 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v4 uses: actions/checkout@v5
with: with:
persist-credentials: false persist-credentials: false

View File

@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Github Code - name: Checkout Github Code
uses: actions/checkout@v4 uses: actions/checkout@v5
- name: Auto Creating Tags For Contrib Packages - name: Auto Creating Tags For Contrib Packages
run: | run: |

2
.gitignore vendored
View File

@ -23,3 +23,5 @@ go.work.sum
node_modules node_modules
.docusaurus .docusaurus
output output
.example/
.golangci.bck.yml

View File

@ -1,325 +1,220 @@
## This file contains all available configuration options version: "2"
## with their default values.
# See https://github.com/golangci/golangci-lint#config-file
# See https://golangci-lint.run/usage/configuration/
# Options for analysis running.
run: run:
# Timeout for analysis, e.g. 30s, 5m.
# Default: 1m
timeout: 5m
# Exit code when at least one issue was found.
# Default: 1
issues-exit-code: 2
# Include test files or not.
# Default: true
tests: false
# List of build tags, all linters use it.
# Default: []
build-tags: []
# If set, we pass it to "go list -mod={option}". From "go help modules":
# If invoked with -mod=readonly, the go command is disallowed from the implicit
# automatic updating of go.mod described above. Instead, it fails when any changes
# to go.mod are needed. This setting is most useful to check that go.mod does
# not need updates, such as in a continuous integration and testing system.
# If invoked with -mod=vendor, the go command assumes that the vendor
# directory holds the correct copies of dependencies and ignores
# the dependency descriptions in go.mod.
#
# Allowed values: readonly|vendor|mod
# Default: ""
modules-download-mode: readonly
# Allow multiple parallel golangci-lint instances running.
# If false, golangci-lint acquires file lock on start.
# Default: false
allow-parallel-runners: true
# Allow multiple golangci-lint instances running, but serialize them around a lock.
# If false, golangci-lint exits with an error if it fails to acquire file lock on start.
# Default: false
allow-serial-runners: true
# Define the Go version limit.
# Mainly related to generics support since go1.18.
# Default: use Go version from the go.mod file, fallback on the env var `GOVERSION`, fallback on 1.17
go: '1.20'
# Number of operating system threads (`GOMAXPROCS`) that can execute golangci-lint simultaneously.
# If it is explicitly set to 0 (i.e. not the default) then golangci-lint will automatically set the value to match Linux container CPU quota.
# Default: the number of logical CPUs in the machine
concurrency: 4 concurrency: 4
go: "1.25"
modules-download-mode: readonly
# Main linters configurations. issues-exit-code: 2
# See https://golangci-lint.run/usage/linters tests: false
allow-parallel-runners: true
allow-serial-runners: true
linters: linters:
# Disable all default enabled linters. default: none
disable-all: true
# Custom enable linters we want to use.
enable: enable:
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. - errcheck
- errchkjson # Checks types passed to the JSON encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. - errchkjson
- funlen # Tool for detection of long functions - funlen
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification - goconst
- goimports # Check import statements are formatted according to the 'goimport' command. Reformat imports in autofix mode. - gocritic
- gci # Gci controls Go package import order and makes it always deterministic. - govet
- goconst # Finds repeated strings that could be replaced by a constant - misspell
- gocritic # Provides diagnostics that check for bugs, performance and style issues. - nolintlint
- gosimple # Linter for Go source code that specializes in simplifying code - revive
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - staticcheck
- misspell # Finds commonly misspelled English words in comments - usestdlibvars
- nolintlint # Reports ill-formed or insufficient nolint directives - whitespace
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. settings:
- staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. funlen:
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code lines: 340
- usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. statements: -1
- whitespace # Tool for detection of leading and trailing whitespace goconst:
match-constant: false
min-len: 4
issues: min-occurrences: 30
exclude-rules: numbers: true
# helpers in tests often (rightfully) pass a *testing.T as their first argument min: 5
- path: _test\.go max: 20
text: "context.Context should be the first parameter of a function" ignore-calls: false
linters: gocritic:
- revive disabled-checks:
# Yes, they are, but it's okay in a test - ifElseChain
- path: _test\.go - assignOp
text: "exported func.*returns unexported type.*which can be annoying to use" - appendAssign
linters: - singleCaseSwitch
- revive - regexpMust
# https://github.com/go-critic/go-critic/issues/926 - typeSwitchVar
- linters: - elseif
- gocritic govet:
text: "unnecessaryDefer:" disable:
- asmdecl
- assign
# https://golangci-lint.run/usage/linters - atomic
linters-settings: - atomicalign
# https://golangci-lint.run/usage/linters/#misspell - bools
misspell: - buildtag
locale: US - cgocall
ignore-words: - composites
- cancelled - copylocks
# https://golangci-lint.run/usage/linters/#gofmt - deepequalerrors
gofmt: - errorsas
# Simplify code: gofmt with `-s` option. - fieldalignment
# Default: true - findcall
simplify: true - framepointer
# Apply the rewrite rules to the source before reformatting. - httpresponse
# https://pkg.go.dev/cmd/gofmt - ifaceassert
# Default: [] - loopclosure
rewrite-rules: [ ] - lostcancel
# - pattern: 'interface{}' - nilfunc
# replacement: 'any' - nilness
# - pattern: 'a[b:len(a)]' - reflectvaluecompare
# replacement: 'a[b:]' - shift
goimports: - shadow
# A comma-separated list of prefixes, which, if set, checks import paths - sigchanyzer
# with the given prefixes are grouped after 3rd-party packages. - sortslice
# Default: "" - stdmethods
local-prefixes: github.com/gogf/gf/v2 - stringintconv
gci: - structtag
# Section configuration to compare against. - testinggoroutine
# Section names are case-insensitive and may contain parameters in (). - tests
# The default order of sections is `standard > default > custom > blank > dot > alias > localmodule`, - unmarshal
# If `custom-order` is `true`, it follows the order of `sections` option. - unreachable
# Default: ["standard", "default"] - unsafeptr
sections: - unusedwrite
- standard # Standard section: captures all standard packages. enable-all: true
- blank # Blank section: contains all blank imports. This section is not present unless explicitly enabled. settings:
- default # Default section: contains all imports that could not be matched to another section type. printf:
- dot # Dot section: contains all dot imports. This section is not present unless explicitly enabled. funcs:
# - alias # Alias section: contains all alias imports. This section is not present unless explicitly enabled. - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
# - localmodule # Local module section: contains all local packages. This section is not present unless explicitly enabled. - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- prefix(github.com/gogf/gf) # Custom section: groups all imports with the specified Prefix. - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- prefix(github.com/gogf/gf/cmd) # Custom section: groups all imports with the specified Prefix. - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
- prefix(github.com/gogf/gfcontrib) # Custom section: groups all imports with the specified Prefix. unusedresult:
- prefix(github.com/gogf/gf/example) # Custom section: groups all imports with the specified Prefix. funcs:
# Skip generated files. - pkg.MyFunc
# Default: true - context.WithCancel
skip-generated: true stringmethods:
# Enable custom order of sections. - MyMethod
# If `true`, make the section order the same as the order of `sections`. misspell:
# Default: false locale: US
custom-order: true ignore-rules:
# Drops lexical ordering for custom sections. - cancelled
# Default: false revive:
no-lex-order: false severity: error
# https://golangci-lint.run/usage/linters/#revive rules:
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md - name: atomic
revive: - name: line-length-limit
ignore-generated-header: true arguments:
severity: error - 380
severity: error
- name: unhandled-error
severity: warning
disabled: true
- name: var-naming
arguments:
- - ID
- URL
- IP
- HTTP
- JSON
- API
- UID
- Id
- Api
- Uid
- Http
- Json
- Ip
- Url
- - VM
severity: warning
disabled: true
- name: string-format
arguments:
- - core.WriteError[1].Message
- /^([^A-Z]|$)/
- must not start with a capital letter
- - fmt.Errorf[0]
- /(^|[^\.!?])$/
- must not end in punctuation
- - panic
- /^[^\n]*$/
- must not contain line breaks
severity: warning
disabled: false
- name: function-result-limit
arguments:
- 4
severity: warning
disabled: false
staticcheck:
checks: [ "all","-S1000","-S1009","-S1016","-S1023","-S1025","-S1029","-S1034","-S1040","-SA1016","-SA1019","-SA1029","-SA4006","-SA4015","-SA6003","-SA9003","-ST1003","-QF1001","-QF1002","-QF1003","-QF1006","-QF1007","-QF1008","-QF1011","-QF1012","-ST1011" ]
initialisms: [ "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS", "SIP", "RTP", "AMQP", "DB", "TS" ]
dot-import-whitelist: [ "fmt" ]
http-status-code-whitelist: [ "200", "400", "404", "500" ]
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules: rules:
- name: atomic - linters:
- name: line-length-limit - revive
severity: error path: _test\.go
arguments: [ 380 ] text: context.Context should be the first parameter of a function
- name: unhandled-error - linters:
severity: warning - revive
disabled: true path: _test\.go
arguments: [] text: exported func.*returns unexported type.*which can be annoying to use
- name: var-naming - linters:
severity: warning - gocritic
disabled: true text: 'unnecessaryDefer:'
arguments: - linters:
# AllowList - goconst
- [ "ID","URL","IP","HTTP","JSON","API","UID","Id","Api","Uid","Http","Json","Ip","Url" ] path: (.+)_test\.go
# DenyList paths:
- [ "VM" ] - third_party$
- name: string-format - builtin$
severity: warning - examples$
disabled: false formatters:
arguments: enable:
- - 'core.WriteError[1].Message' - gci
- '/^([^A-Z]|$)/' - gofmt
- must not start with a capital letter - goimports
- - 'fmt.Errorf[0]' settings:
- '/(^|[^\.!?])$/' gci:
- must not end in punctuation sections:
- - panic - standard
- '/^[^\n]*$/' - blank
- must not contain line breaks - default
- name: function-result-limit - dot
severity: warning - prefix(github.com/gogf/gf/v2)
disabled: false - prefix(github.com/gogf/gf/cmd)
arguments: [ 4 ] - prefix(github.com/gogf/gfcontrib)
- prefix(github.com/gogf/gf/example)
# https://golangci-lint.run/usage/linters/#funlen custom-order: true
funlen: no-lex-order: false
# Checks the number of lines in a function. gofmt:
# If lower than 0, disable the check. simplify: true
# Default: 60 rewrite-rules:
lines: 340 - pattern: 'interface{}'
# Checks the number of statements in a function. replacement: 'any'
# If lower than 0, disable the check. - pattern: 'reflect.Ptr'
# Default: 40 replacement: 'reflect.Pointer'
statements: -1 - pattern: 'ioutil.ReadAll'
replacement: 'io.ReadAll'
# https://golangci-lint.run/usage/linters/#goconst - pattern: 'ioutil.WriteFile'
goconst: replacement: 'os.WriteFile'
# Minimal length of string constant. - pattern: 'ioutil.ReadFile'
# Default: 3 replacement: 'os.ReadFile'
min-len: 4 - pattern: 'ioutil.NopCloser'
# Minimum occurrences of constant string count to trigger issue. replacement: 'io.NopCloser'
# Default: 3 goimports:
# For subsequent optimization, the value is reduced. local-prefixes:
min-occurrences: 30 - github.com/gogf/gf/v2
# Ignore test files. exclusions:
# Default: false generated: lax
ignore-tests: true paths:
# Look for existing constants matching the values. - third_party$
# Default: true - builtin$
match-constant: false - examples$
# Search also for duplicated numbers.
# Default: false
numbers: true
# Minimum value, only works with goconst.numbers
# Default: 3
min: 5
# Maximum value, only works with goconst.numbers
# Default: 3
max: 20
# Ignore when constant is not used as function argument.
# Default: true
ignore-calls: false
# https://golangci-lint.run/usage/linters/#gocritic
gocritic:
disabled-checks:
- ifElseChain
- assignOp
- appendAssign
- singleCaseSwitch
- regexpMust
- typeSwitchVar
- elseif
# https://golangci-lint.run/usage/linters/#gosimple
gosimple:
# Sxxxx checks in https://staticcheck.io/docs/configuration/options/#checks
# Default: ["*"]
checks: [
"all", "-S1000", "-S1001", "-S1002", "-S1008", "-S1009", "-S1016", "-S1023", "-S1025", "-S1029", "-S1034", "-S1040"
]
# https://golangci-lint.run/usage/linters/#govet
govet:
# Report about shadowed variables.
# Default: false
# check-shadowing: true
# Settings per analyzer.
settings:
# Analyzer name, run `go tool vet help` to see all analyzers.
printf:
# Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`).
# Default: []
funcs:
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
# shadow:
# Whether to be strict about shadowing; can be noisy.
# Default: false
# strict: false
unusedresult:
# Comma-separated list of functions whose results must be used
# (in addition to defaults context.WithCancel,context.WithDeadline,context.WithTimeout,context.WithValue,
# errors.New,fmt.Errorf,fmt.Sprint,fmt.Sprintf,sort.Reverse)
# Default []
funcs:
- pkg.MyFunc
- context.WithCancel
# Comma-separated list of names of methods of type func() string whose results must be used
# (in addition to default Error,String)
# Default []
stringmethods:
- MyMethod
# Enable all analyzers.
# Default: false
enable-all: true
# Disable analyzers by name.
# Run `go tool vet help` to see all analyzers.
# Default: []
disable:
- asmdecl
- assign
- atomic
- atomicalign
- bools
- buildtag
- cgocall
- composites
- copylocks
- deepequalerrors
- errorsas
- fieldalignment
- findcall
- framepointer
- httpresponse
- ifaceassert
- loopclosure
- lostcancel
- nilfunc
- nilness
- reflectvaluecompare
- shift
- shadow
- sigchanyzer
- sortslice
- stdmethods
- stringintconv
- structtag
- testinggoroutine
- tests
- unmarshal
- unreachable
- unsafeptr
- unusedwrite
# https://golangci-lint.run/usage/linters/#staticcheck
staticcheck:
# SAxxxx checks in https://staticcheck.io/docs/configuration/options/#checks
# Default: ["*"]
checks: [ "all","-SA1019","-SA4015","-SA1029","-SA1016","-SA9003","-SA4006","-SA6003" ]

View File

@ -4,6 +4,8 @@
[![Go Reference](https://pkg.go.dev/badge/github.com/gogf/gf/v2.svg)](https://pkg.go.dev/github.com/gogf/gf/v2) [![Go Reference](https://pkg.go.dev/badge/github.com/gogf/gf/v2.svg)](https://pkg.go.dev/github.com/gogf/gf/v2)
[![GoFrame CI](https://github.com/gogf/gf/actions/workflows/ci-main.yml/badge.svg)](https://github.com/gogf/gf/actions/workflows/ci-main.yml) [![GoFrame CI](https://github.com/gogf/gf/actions/workflows/ci-main.yml/badge.svg)](https://github.com/gogf/gf/actions/workflows/ci-main.yml)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/gogf/gf/badge)](https://scorecard.dev/viewer/?uri=github.com/gogf/gf)
[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/9233/badge)](https://bestpractices.coreinfrastructure.org/projects/9233)
[![Go Report Card](https://goreportcard.com/badge/github.com/gogf/gf/v2)](https://goreportcard.com/report/github.com/gogf/gf/v2) [![Go Report Card](https://goreportcard.com/badge/github.com/gogf/gf/v2)](https://goreportcard.com/report/github.com/gogf/gf/v2)
[![Code Coverage](https://codecov.io/gh/gogf/gf/branch/master/graph/badge.svg)](https://codecov.io/gh/gogf/gf) [![Code Coverage](https://codecov.io/gh/gogf/gf/branch/master/graph/badge.svg)](https://codecov.io/gh/gogf/gf)
[![Production Ready](https://img.shields.io/badge/production-ready-blue.svg?style=flat)](https://github.com/gogf/gf) [![Production Ready](https://img.shields.io/badge/production-ready-blue.svg?style=flat)](https://github.com/gogf/gf)
@ -36,7 +38,7 @@ A powerful framework for faster, easier, and more efficient project development.
💖 [Thanks to all the contributors who made GoFrame possible](https://github.com/gogf/gf/graphs/contributors) 💖 💖 [Thanks to all the contributors who made GoFrame possible](https://github.com/gogf/gf/graphs/contributors) 💖
<a href="https://github.com/gogf/gf/graphs/contributors"> <a href="https://github.com/gogf/gf/graphs/contributors">
<img src="https://goframe.org/img/contributors.svg?version=v2.9.0-beta" alt="goframe contributors"/> <img src="https://goframe.org/img/contributors.svg?version=v2.9.0" alt="goframe contributors"/>
</a> </a>
# License # License

View File

@ -1,33 +1,33 @@
module github.com/gogf/gf/cmd/gf/v2 module github.com/gogf/gf/cmd/gf/v2
go 1.22 go 1.23.0
require ( require (
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.0-beta github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.2
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.0-beta github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.2
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.0-beta github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.2
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.0-beta github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.2
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.0-beta github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.2
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.0-beta github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.2
github.com/gogf/gf/v2 v2.9.0-beta github.com/gogf/gf/v2 v2.9.2
github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f
github.com/olekukonko/tablewriter v0.0.5 github.com/olekukonko/tablewriter v1.0.9
github.com/schollz/progressbar/v3 v3.15.0 github.com/schollz/progressbar/v3 v3.15.0
golang.org/x/mod v0.17.0 golang.org/x/mod v0.26.0
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d golang.org/x/tools v0.35.0
) )
require ( require (
aead.dev/minisign v0.2.0 // indirect aead.dev/minisign v0.2.0 // indirect
github.com/BurntSushi/toml v1.4.0 // indirect github.com/BurntSushi/toml v1.5.0 // indirect
github.com/ClickHouse/clickhouse-go/v2 v2.0.15 // indirect github.com/ClickHouse/clickhouse-go/v2 v2.0.15 // indirect
github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect
github.com/emirpasic/gods v1.18.1 // indirect github.com/emirpasic/gods v1.18.1 // indirect
github.com/fatih/color v1.18.0 // indirect github.com/fatih/color v1.18.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/glebarez/go-sqlite v1.21.2 // indirect github.com/glebarez/go-sqlite v1.21.2 // indirect
github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-sql-driver/mysql v1.7.1 // indirect github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
@ -36,28 +36,31 @@ require (
github.com/gorilla/websocket v1.5.3 // indirect github.com/gorilla/websocket v1.5.3 // indirect
github.com/grokify/html-strip-tags-go v0.1.0 // indirect github.com/grokify/html-strip-tags-go v0.1.0 // indirect
github.com/lib/pq v1.10.9 // indirect github.com/lib/pq v1.10.9 // indirect
github.com/magiconair/properties v1.8.9 // indirect github.com/magiconair/properties v1.8.10 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/microsoft/go-mssqldb v1.7.1 // indirect github.com/microsoft/go-mssqldb v1.7.1 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/olekukonko/errors v1.1.0 // indirect
github.com/olekukonko/ll v0.0.9 // indirect
github.com/paulmach/orb v0.7.1 // indirect github.com/paulmach/orb v0.7.1 // indirect
github.com/pierrec/lz4/v4 v4.1.14 // indirect github.com/pierrec/lz4/v4 v4.1.14 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect github.com/rivo/uniseg v0.4.7 // indirect
github.com/shopspring/decimal v1.3.1 // indirect github.com/shopspring/decimal v1.3.1 // indirect
github.com/sijms/go-ora/v2 v2.7.10 // indirect github.com/sijms/go-ora/v2 v2.7.10 // indirect
go.opentelemetry.io/otel v1.32.0 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/otel/metric v1.32.0 // indirect go.opentelemetry.io/otel v1.37.0 // indirect
go.opentelemetry.io/otel/sdk v1.32.0 // indirect go.opentelemetry.io/otel/metric v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.32.0 // indirect go.opentelemetry.io/otel/sdk v1.37.0 // indirect
golang.org/x/crypto v0.31.0 // indirect go.opentelemetry.io/otel/trace v1.37.0 // indirect
golang.org/x/net v0.33.0 // indirect golang.org/x/crypto v0.41.0 // indirect
golang.org/x/sync v0.10.0 // indirect golang.org/x/net v0.43.0 // indirect
golang.org/x/sys v0.28.0 // indirect golang.org/x/sync v0.16.0 // indirect
golang.org/x/term v0.27.0 // indirect golang.org/x/sys v0.35.0 // indirect
golang.org/x/text v0.21.0 // indirect golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.22.5 // indirect modernc.org/libc v1.22.5 // indirect
modernc.org/mathutil v1.5.0 // indirect modernc.org/mathutil v1.5.0 // indirect

View File

@ -12,8 +12,8 @@ github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 h1:D3occ
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0/go.mod h1:bTSOgj05NGRuHHhQwAdPnYr9TOdNmKlZTgGLL6nyAdI= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0/go.mod h1:bTSOgj05NGRuHHhQwAdPnYr9TOdNmKlZTgGLL6nyAdI=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA= github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/ClickHouse/clickhouse-go v1.5.4/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI= github.com/ClickHouse/clickhouse-go v1.5.4/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI=
github.com/ClickHouse/clickhouse-go/v2 v2.0.15 h1:lLAZliqrZEygkxosLaW1qHyeTb4Ho7fVCZ0WKCpLocU= github.com/ClickHouse/clickhouse-go/v2 v2.0.15 h1:lLAZliqrZEygkxosLaW1qHyeTb4Ho7fVCZ0WKCpLocU=
github.com/ClickHouse/clickhouse-go/v2 v2.0.15/go.mod h1:Z21o82zD8FFqefOQDg93c0XITlxGbTsWQuRm588Azkk= github.com/ClickHouse/clickhouse-go/v2 v2.0.15/go.mod h1:Z21o82zD8FFqefOQDg93c0XITlxGbTsWQuRm588Azkk=
@ -31,14 +31,14 @@ github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo= github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k= github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 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 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM= github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM=
@ -58,8 +58,8 @@ github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EO
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@ -84,14 +84,12 @@ github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/magiconair/properties v1.8.9 h1:nWcCbLq1N2v/cpNsy5WvQ37Fb+YElfq20WJ/a8RkpQM= github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
github.com/magiconair/properties v1.8.9/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
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 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
@ -100,8 +98,12 @@ github.com/microsoft/go-mssqldb v1.7.1/go.mod h1:kOvZKUdrhhFQmxLZqbwUV0rHkNkZpth
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ= github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
github.com/mkevac/debugcharts v0.0.0-20191222103121-ae1c48aa8615/go.mod h1:Ad7oeElCZqA1Ufj0U9/liOF4BtVepxRcTvr2ey7zTvM= github.com/mkevac/debugcharts v0.0.0-20191222103121-ae1c48aa8615/go.mod h1:Ad7oeElCZqA1Ufj0U9/liOF4BtVepxRcTvr2ey7zTvM=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI=
github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g=
github.com/olekukonko/tablewriter v1.0.9 h1:XGwRsYLC2bY7bNd93Dk51bcPZksWZmLYuaTHR0FqfL8=
github.com/olekukonko/tablewriter v1.0.9/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=
github.com/paulmach/orb v0.7.1 h1:Zha++Z5OX/l168sqHK3k4z18LDvr+YAO/VjK0ReQ9rU= github.com/paulmach/orb v0.7.1 h1:Zha++Z5OX/l168sqHK3k4z18LDvr+YAO/VjK0ReQ9rU=
github.com/paulmach/orb v0.7.1/go.mod h1:FWRlTgl88VI1RBx/MkrwWDRhQ96ctqMCh8boXhmqB/A= github.com/paulmach/orb v0.7.1/go.mod h1:FWRlTgl88VI1RBx/MkrwWDRhQ96ctqMCh8boXhmqB/A=
github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY= github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY=
@ -118,8 +120,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qq
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/schollz/progressbar/v3 v3.15.0 h1:cNZmcNiVyea6oofBTg80ZhVXxf3wG/JoAhqCCwopkQo= github.com/schollz/progressbar/v3 v3.15.0 h1:cNZmcNiVyea6oofBTg80ZhVXxf3wG/JoAhqCCwopkQo=
github.com/schollz/progressbar/v3 v3.15.0/go.mod h1:ncBdc++eweU0dQoeZJ3loXoAc+bjaallHRIm8pVVeQM= github.com/schollz/progressbar/v3 v3.15.0/go.mod h1:ncBdc++eweU0dQoeZJ3loXoAc+bjaallHRIm8pVVeQM=
github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
@ -141,37 +143,41 @@ github.com/tklauser/numcpus v0.4.0/go.mod h1:1+UI3pD8NW14VMwdgJNJ1ESk2UnwhAnz5hM
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/otel v1.7.0/go.mod h1:5BdUoMIz5WEs0vt0CUEMtSSaTSHBBVwrhnz7+nrD5xk= go.opentelemetry.io/otel v1.7.0/go.mod h1:5BdUoMIz5WEs0vt0CUEMtSSaTSHBBVwrhnz7+nrD5xk=
go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4= go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU= go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
go.opentelemetry.io/otel/trace v1.7.0/go.mod h1:fzLSB9nqR2eXzxPXb2JW9IKE+ScyXA48yyE4TNvoHqU= go.opentelemetry.io/otel/trace v1.7.0/go.mod h1:fzLSB9nqR2eXzxPXb2JW9IKE+ScyXA48yyE4TNvoHqU=
go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 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.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 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/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/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-20190620200207-3b0461eec859/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-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-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/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-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-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@ -181,25 +187,24 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32/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.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8= golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8=
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 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.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/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-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 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-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-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@ -1,8 +1,6 @@
go 1.22 go 1.23.0
use ( use ./
./
)
// ===================================================================================================== // =====================================================================================================
// NOTE: // NOTE:

View File

@ -11,6 +11,8 @@ import (
"context" "context"
"github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/renderer"
"github.com/olekukonko/tablewriter/tw"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/os/gproc"
@ -61,10 +63,23 @@ func (c cEnv) Index(ctx context.Context, in cEnvInput) (out *cEnvOutput, err err
} }
array = append(array, []string{gstr.Trim(match[1]), gstr.Trim(match[2])}) array = append(array, []string{gstr.Trim(match[1]), gstr.Trim(match[2])})
} }
tw := tablewriter.NewWriter(buffer) table := tablewriter.NewTable(buffer,
tw.SetColumnAlignment([]int{tablewriter.ALIGN_LEFT, tablewriter.ALIGN_LEFT}) tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
tw.AppendBulk(array) Settings: tw.Settings{
tw.Render() Separators: tw.Separators{BetweenRows: tw.Off, BetweenColumns: tw.On},
},
Symbols: tw.NewSymbols(tw.StyleASCII),
})),
tablewriter.WithConfig(tablewriter.Config{
Row: tw.CellConfig{
Formatting: tw.CellFormatting{AutoWrap: tw.WrapNone},
Alignment: tw.CellAlignment{PerColumn: []tw.Align{tw.AlignLeft, tw.AlignLeft}},
ColMaxWidths: tw.CellWidth{Global: 84},
},
}),
)
table.Bulk(array)
table.Render()
mlog.Print(buffer.String()) mlog.Print(buffer.String())
return return
} }

View File

@ -104,7 +104,7 @@ func Test_Build_Single_VarMap(t *testing.T) {
t.Assert(gfile.Exists(binaryPath), false) t.Assert(gfile.Exists(binaryPath), false)
_, err = f.Index(ctx, cBuildInput{ _, err = f.Index(ctx, cBuildInput{
VarMap: map[string]interface{}{ VarMap: map[string]any{
"a": "1", "a": "1",
"b": "2", "b": "2",
}, },

View File

@ -378,7 +378,7 @@ func Test_Gen_Dao_Issue3459(t *testing.T) {
filepath.FromSlash(testPath + "/model/do/table_user.go"), filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"), filepath.FromSlash(testPath + "/model/entity/table_user.go"),
} }
for i, _ := range files { for i := range files {
//_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i])) //_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i]))
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
} }
@ -450,7 +450,7 @@ func Test_Gen_Dao_Issue3749(t *testing.T) {
filepath.FromSlash(testPath + "/model/do/table_user.go"), filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"), filepath.FromSlash(testPath + "/model/entity/table_user.go"),
} }
for i, _ := range files { for i := range files {
//_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i])) //_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i]))
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
} }

View File

@ -26,25 +26,34 @@ func Test_Gen_Dao_Sharding(t *testing.T) {
tableSingle = "single_table" tableSingle = "single_table"
table1 = "users_0001" table1 = "users_0001"
table2 = "users_0002" table2 = "users_0002"
table3 = "users_0003" table3 = "orders_0001"
table4 = "orders_0002"
sqlFilePath = gtest.DataPath(`gendao`, `sharding`, `sharding.sql`) sqlFilePath = gtest.DataPath(`gendao`, `sharding`, `sharding.sql`)
) )
dropTableWithDb(db, tableSingle)
dropTableWithDb(db, table1)
dropTableWithDb(db, table2)
dropTableWithDb(db, table3)
dropTableWithDb(db, table4)
t.AssertNil(execSqlFile(db, sqlFilePath)) t.AssertNil(execSqlFile(db, sqlFilePath))
defer dropTableWithDb(db, tableSingle) defer dropTableWithDb(db, tableSingle)
defer dropTableWithDb(db, table1) defer dropTableWithDb(db, table1)
defer dropTableWithDb(db, table2) defer dropTableWithDb(db, table2)
defer dropTableWithDb(db, table3) defer dropTableWithDb(db, table3)
defer dropTableWithDb(db, table4)
var ( var (
path = gfile.Temp(guid.S()) path = gfile.Temp(guid.S())
//path = "/Users/john/Temp/gen_dao_sharding" // path = "/Users/john/Temp/gen_dao_sharding"
group = "test" group = "test"
in = gendao.CGenDaoInput{ in = gendao.CGenDaoInput{
Path: path, Path: path,
Link: link, Link: link,
Group: group, Group: group,
Prefix: "",
ShardingPattern: []string{ ShardingPattern: []string{
`users_?`, `users_?`,
`orders_?`,
}, },
} }
) )
@ -65,13 +74,16 @@ func Test_Gen_Dao_Sharding(t *testing.T) {
generatedFiles, err := gfile.ScanDir(path, "*.go", true) generatedFiles, err := gfile.ScanDir(path, "*.go", true)
t.AssertNil(err) t.AssertNil(err)
t.Assert(len(generatedFiles), 8) t.Assert(len(generatedFiles), 12)
var ( var (
daoSingleTableContent = gfile.GetContents(gfile.Join(path, "dao", "single_table.go")) daoSingleTableContent = gfile.GetContents(gfile.Join(path, "dao", "single_table.go"))
daoUsersContent = gfile.GetContents(gfile.Join(path, "dao", "users.go")) daoUsersContent = gfile.GetContents(gfile.Join(path, "dao", "users.go"))
daoOrdersContent = gfile.GetContents(gfile.Join(path, "dao", "orders.go"))
) )
t.Assert(gstr.Contains(daoSingleTableContent, "SingleTable = singleTableDao{internal.NewSingleTableDao()}"), true) t.Assert(gstr.Contains(daoSingleTableContent, "SingleTable = singleTableDao{internal.NewSingleTableDao()}"), true)
t.Assert(gstr.Contains(daoUsersContent, "Users = usersDao{internal.NewUsersDao(userShardingHandler)}"), true) t.Assert(gstr.Contains(daoUsersContent, "Users = usersDao{internal.NewUsersDao(usersShardingHandler)}"), true)
t.Assert(gstr.Contains(daoUsersContent, "m.Sharding(gdb.ShardingConfig{"), true) t.Assert(gstr.Contains(daoUsersContent, "m.Sharding(gdb.ShardingConfig{"), true)
t.Assert(gstr.Contains(daoOrdersContent, "Orders = ordersDao{internal.NewOrdersDao(ordersShardingHandler)}"), true)
t.Assert(gstr.Contains(daoOrdersContent, "m.Sharding(gdb.ShardingConfig{"), true)
}) })
} }

View File

@ -107,7 +107,7 @@ func Test_Gen_Dao_Default(t *testing.T) {
filepath.FromSlash(testPath + "/model/do/table_user.go"), filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"), filepath.FromSlash(testPath + "/model/entity/table_user.go"),
} }
for i, _ := range files { for i := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
} }
}) })
@ -208,7 +208,7 @@ func Test_Gen_Dao_TypeMapping(t *testing.T) {
filepath.FromSlash(testPath + "/model/do/table_user.go"), filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"), filepath.FromSlash(testPath + "/model/entity/table_user.go"),
} }
for i, _ := range files { for i := range files {
//_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i])) //_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i]))
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
} }
@ -311,7 +311,7 @@ func Test_Gen_Dao_FieldMapping(t *testing.T) {
filepath.FromSlash(testPath + "/model/do/table_user.go"), filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"), filepath.FromSlash(testPath + "/model/entity/table_user.go"),
} }
for i, _ := range files { for i := range files {
//_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i])) //_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i]))
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
} }
@ -403,7 +403,7 @@ func Test_Gen_Dao_Sqlite3(t *testing.T) {
filepath.FromSlash(testPath + "/model/do/table_user.go"), filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"), filepath.FromSlash(testPath + "/model/entity/table_user.go"),
} }
for i, _ := range files { for i := range files {
//_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i])) //_ = gfile.PutContents(expectFiles[i], gfile.GetContents(files[i]))
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
} }

View File

@ -367,3 +367,145 @@ func Test_Issue_3955(t *testing.T) {
} }
}) })
} }
func Test_Issue_4330_TypeMapping_Ineffective(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`issue`, `3685`, `user.tpl.sql`),
table,
)
)
dropTableWithDb(db, table)
array := gstr.SplitAndTrim(sqlContent, ";")
for _, v := range array {
if _, err = db.Exec(ctx, v); err != nil {
t.AssertNil(err)
}
}
defer dropTableWithDb(db, table)
var (
path = gfile.Temp(guid.S())
in = genpbentity.CGenPbEntityInput{
Path: path,
Package: "",
Link: link,
Tables: "",
Prefix: "",
RemovePrefix: "",
RemoveFieldPrefix: "",
NameCase: "",
JsonCase: "",
Option: "",
TypeMapping: map[genpbentity.DBFieldTypeName]genpbentity.CustomAttributeType{
"json": {
Type: "google.protobuf.Value",
Import: "google/protobuf/struct.proto",
},
"decimal": {
Type: "double",
},
},
FieldMapping: nil,
}
)
err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)
err = gfile.Mkdir(path)
t.AssertNil(err)
defer gfile.Remove(path)
_, err = genpbentity.CGenPbEntity{}.PbEntity(ctx, in)
t.AssertNil(err)
// files
files, err := gfile.ScanDir(path, "*.proto", false)
t.AssertNil(err)
t.Assert(files, []string{
path + filepath.FromSlash("/table_user.proto"),
})
// contents
testPath := gtest.DataPath("issue", "4330")
expectFiles := []string{
testPath + filepath.FromSlash("/issue4330_double.proto"),
}
for i := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
}
})
}
func Test_Gen_Pbentity_Sharding(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
tableSingle = "single_table"
table1 = "users_0001"
table2 = "users_0002"
table3 = "orders_0001"
table4 = "orders_0002"
sqlFilePath = gtest.DataPath(`gendao`, `sharding`, `sharding.sql`)
)
dropTableWithDb(db, tableSingle)
dropTableWithDb(db, table1)
dropTableWithDb(db, table2)
dropTableWithDb(db, table3)
dropTableWithDb(db, table4)
t.AssertNil(execSqlFile(db, sqlFilePath))
defer dropTableWithDb(db, tableSingle)
defer dropTableWithDb(db, table1)
defer dropTableWithDb(db, table2)
defer dropTableWithDb(db, table3)
defer dropTableWithDb(db, table4)
var (
path = gfile.Temp(guid.S())
in = genpbentity.CGenPbEntityInput{
Path: path,
Package: "unittest",
Link: link,
Tables: "",
RemovePrefix: "",
RemoveFieldPrefix: "",
NameCase: "",
JsonCase: "",
Option: "",
TypeMapping: nil,
FieldMapping: nil,
ShardingPattern: []string{
`users_?`,
`orders_?`,
},
}
)
err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)
err = gfile.Mkdir(path)
t.AssertNil(err)
defer gfile.Remove(path)
_, err = genpbentity.CGenPbEntity{}.PbEntity(ctx, in)
t.AssertNil(err)
// files
t.AssertNil(err)
generatedFiles, err := gfile.ScanDir(path, "*.proto", true)
t.Assert(len(generatedFiles), 3)
var (
msgSingleTableContent = gfile.GetContents(gfile.Join(path, "single_table.proto"))
msgUsersContent = gfile.GetContents(gfile.Join(path, "users.proto"))
msgOrdersContent = gfile.GetContents(gfile.Join(path, "orders.proto"))
)
t.Assert(gstr.Contains(msgSingleTableContent, "message SingleTable {"), true)
t.Assert(gstr.Contains(msgUsersContent, "message Users {"), true)
t.Assert(gstr.Contains(msgOrdersContent, "message Orders {"), true)
})
}

View File

@ -9,13 +9,14 @@ package genctrl
import ( import (
"context" "context"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gtag" "github.com/gogf/gf/v2/util/gtag"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
) )
const ( const (

View File

@ -11,6 +11,9 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/renderer"
"github.com/olekukonko/tablewriter/tw"
"golang.org/x/mod/modfile" "golang.org/x/mod/modfile"
"github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/garray"
@ -99,6 +102,20 @@ var (
Type: "float64", Type: "float64",
}, },
} }
// tablewriter Options
twRenderer = tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
Borders: tw.Border{Top: tw.Off, Bottom: tw.Off, Left: tw.Off, Right: tw.Off},
Settings: tw.Settings{
Separators: tw.Separators{BetweenRows: tw.Off, BetweenColumns: tw.Off},
},
Symbols: tw.NewSymbols(tw.StyleASCII),
}))
twConfig = tablewriter.WithConfig(tablewriter.Config{
Row: tw.CellConfig{
Formatting: tw.CellFormatting{AutoWrap: tw.WrapNone},
},
})
) )
func (c CGenDao) Dao(ctx context.Context, in CGenDaoInput) (out *CGenDaoOutput, err error) { func (c CGenDao) Dao(ctx context.Context, in CGenDaoInput) (out *CGenDaoOutput, err error) {
@ -219,14 +236,18 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
tableNames[i] = "" tableNames[i] = ""
continue continue
} }
shardingNewTableSet.Add(newTableName) // Add prefix to sharding table name, if not, the isSharding check would not match.
shardingNewTableSet.Add(in.Prefix + newTableName)
} }
} }
newTableName = in.Prefix + newTableName newTableName = in.Prefix + newTableName
newTableNames[i] = newTableName if tableNames[i] != "" {
// If shardingNewTableSet contains newTableName (tableName is empty), it should not be added to tableNames, make it empty and filter later.
newTableNames[i] = newTableName
}
} }
tableNames = garray.NewStrArrayFrom(tableNames).FilterEmpty().Slice() tableNames = garray.NewStrArrayFrom(tableNames).FilterEmpty().Slice()
newTableNames = garray.NewStrArrayFrom(newTableNames).FilterEmpty().Slice() // Filter empty table names. make sure that newTableNames and tableNames have the same length.
in.genItems.Scale() in.genItems.Scale()
// Dao: index and internal. // Dao: index and internal.

View File

@ -127,6 +127,7 @@ func generateDaoIndex(in generateDaoIndexInput) {
tplView.ClearAssigns() tplView.ClearAssigns()
tplView.Assigns(gview.Params{ tplView.Assigns(gview.Params{
tplVarTableSharding: in.IsSharding, tplVarTableSharding: in.IsSharding,
tplVarTableShardingPrefix: in.NewTableName + "_",
tplVarImportPrefix: in.ImportPrefix, tplVarImportPrefix: in.ImportPrefix,
tplVarTableName: in.TableName, tplVarTableName: in.TableName,
tplVarTableNameCamelCase: in.TableNameCamelCase, tplVarTableNameCamelCase: in.TableNameCamelCase,
@ -210,13 +211,9 @@ func generateColumnNamesForDao(fieldMap map[string]*gdb.TableField, removeFieldP
fmt.Sprintf(` #"%s",`, field.Name), fmt.Sprintf(` #"%s",`, field.Name),
} }
} }
tw := tablewriter.NewWriter(buffer) table := tablewriter.NewTable(buffer, twRenderer, twConfig)
tw.SetBorder(false) table.Bulk(array)
tw.SetRowLine(false) table.Render()
tw.SetAutoWrapText(false)
tw.SetColumnSeparator("")
tw.AppendBulk(array)
tw.Render()
namesContent := buffer.String() namesContent := buffer.String()
// Let's do this hack of table writer for indent! // Let's do this hack of table writer for indent!
namesContent = gstr.Replace(namesContent, " #", "") namesContent = gstr.Replace(namesContent, " #", "")
@ -251,13 +248,9 @@ func generateColumnDefinitionForDao(fieldMap map[string]*gdb.TableField, removeF
" #" + fmt.Sprintf(`// %s`, comment), " #" + fmt.Sprintf(`// %s`, comment),
} }
} }
tw := tablewriter.NewWriter(buffer) table := tablewriter.NewTable(buffer, twRenderer, twConfig)
tw.SetBorder(false) table.Bulk(array)
tw.SetRowLine(false) table.Render()
tw.SetAutoWrapText(false)
tw.SetColumnSeparator("")
tw.AppendBulk(array)
tw.Render()
defineContent := buffer.String() defineContent := buffer.String()
// Let's do this hack of table writer for indent! // Let's do this hack of table writer for indent!
defineContent = gstr.Replace(defineContent, " #", "") defineContent = gstr.Replace(defineContent, " #", "")

View File

@ -45,14 +45,14 @@ func generateDo(ctx context.Context, in CGenDaoInternalInput) {
IsDo: true, IsDo: true,
}) })
) )
// replace all types to interface{}. // replace all types to any.
structDefinition, _ = gregex.ReplaceStringFuncMatch( structDefinition, _ = gregex.ReplaceStringFuncMatch(
"([A-Z]\\w*?)\\s+([\\w\\*\\.]+?)\\s+(//)", "([A-Z]\\w*?)\\s+([\\w\\*\\.]+?)\\s+(//)",
structDefinition, structDefinition,
func(match []string) string { func(match []string) string {
// If the type is already a pointer/slice/map, it does nothing. // If the type is already a pointer/slice/map, it does nothing.
if !gstr.HasPrefix(match[2], "*") && !gstr.HasPrefix(match[2], "[]") && !gstr.HasPrefix(match[2], "map") { if !gstr.HasPrefix(match[2], "*") && !gstr.HasPrefix(match[2], "[]") && !gstr.HasPrefix(match[2], "map") {
return fmt.Sprintf(`%s interface{} %s`, match[1], match[3]) return fmt.Sprintf(`%s any %s`, match[1], match[3])
} }
return match[0] return match[0]
}, },

View File

@ -41,22 +41,18 @@ func generateStructDefinition(ctx context.Context, in generateStructDefinitionIn
appendImports = append(appendImports, imports) appendImports = append(appendImports, imports)
} }
} }
tw := tablewriter.NewWriter(buffer) table := tablewriter.NewTable(buffer, twRenderer, twConfig)
tw.SetBorder(false) table.Bulk(array)
tw.SetRowLine(false) table.Render()
tw.SetAutoWrapText(false)
tw.SetColumnSeparator("")
tw.AppendBulk(array)
tw.Render()
stContent := buffer.String() stContent := buffer.String()
// Let's do this hack of table writer for indent! // Let's do this hack of table writer for indent!
stContent = gstr.Replace(stContent, " #", "") stContent = gstr.Replace(stContent, " #", "")
stContent = gstr.Replace(stContent, "` ", "`") stContent = gstr.Replace(stContent, "` ", "`")
stContent = gstr.Replace(stContent, "``", "") stContent = gstr.Replace(stContent, "``", "")
buffer.Reset() buffer.Reset()
buffer.WriteString(fmt.Sprintf("type %s struct {\n", in.StructName)) fmt.Fprintf(buffer, "type %s struct {\n", in.StructName)
if in.IsDo { if in.IsDo {
buffer.WriteString(fmt.Sprintf("g.Meta `orm:\"table:%s, do:true\"`\n", in.TableName)) fmt.Fprintf(buffer, "g.Meta `orm:\"table:%s, do:true\"`\n", in.TableName)
} }
buffer.WriteString(stContent) buffer.WriteString(stContent)
buffer.WriteString("}") buffer.WriteString("}")

View File

@ -97,6 +97,7 @@ generated json tag case for model struct, cases are as follows:
tplVarTableNameCamelCase = `TplTableNameCamelCase` tplVarTableNameCamelCase = `TplTableNameCamelCase`
tplVarTableNameCamelLowerCase = `TplTableNameCamelLowerCase` tplVarTableNameCamelLowerCase = `TplTableNameCamelLowerCase`
tplVarTableSharding = `TplTableSharding` tplVarTableSharding = `TplTableSharding`
tplVarTableShardingPrefix = `TplTableShardingPrefix`
tplVarPackageImports = `TplPackageImports` tplVarPackageImports = `TplPackageImports`
tplVarImportPrefix = `TplImportPrefix` tplVarImportPrefix = `TplImportPrefix`
tplVarStructDefine = `TplStructDefine` tplVarStructDefine = `TplStructDefine`

View File

@ -113,12 +113,12 @@ func (p *EnumsParser) ParsePackage(pkg *packages.Package) {
} }
func (p *EnumsParser) Export() string { func (p *EnumsParser) Export() string {
var typeEnumMap = make(map[string][]interface{}) var typeEnumMap = make(map[string][]any)
for _, enum := range p.enums { for _, enum := range p.enums {
if typeEnumMap[enum.Type] == nil { if typeEnumMap[enum.Type] == nil {
typeEnumMap[enum.Type] = make([]interface{}, 0) typeEnumMap[enum.Type] = make([]any, 0)
} }
var value interface{} var value any
switch enum.Kind { switch enum.Kind {
case constant.Int: case constant.Int:
value = gconv.Int64(enum.Value) value = gconv.Int64(enum.Value)

View File

@ -109,7 +109,7 @@ func (c CGenPb) tagCommentIntoListMap(comment string, lineTagMap *gmap.ListMap)
func (c CGenPb) listMapToStructTag(lineTagMap *gmap.ListMap) string { func (c CGenPb) listMapToStructTag(lineTagMap *gmap.ListMap) string {
var tag string var tag string
lineTagMap.Iterator(func(key, value interface{}) bool { lineTagMap.Iterator(func(key, value any) bool {
if tag != "" { if tag != "" {
tag += " " tag += " "
} }

View File

@ -15,6 +15,8 @@ import (
"strings" "strings"
"github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/renderer"
"github.com/olekukonko/tablewriter/tw"
"github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/container/gset"
@ -37,18 +39,19 @@ type (
CGenPbEntity struct{} CGenPbEntity struct{}
CGenPbEntityInput struct { CGenPbEntityInput struct {
g.Meta `name:"pbentity" config:"{CGenPbEntityConfig}" brief:"{CGenPbEntityBrief}" eg:"{CGenPbEntityEg}" ad:"{CGenPbEntityAd}"` g.Meta `name:"pbentity" config:"{CGenPbEntityConfig}" brief:"{CGenPbEntityBrief}" eg:"{CGenPbEntityEg}" ad:"{CGenPbEntityAd}"`
Path string `name:"path" short:"p" brief:"{CGenPbEntityBriefPath}" d:"manifest/protobuf/pbentity"` Path string `name:"path" short:"p" brief:"{CGenPbEntityBriefPath}" d:"manifest/protobuf/pbentity"`
Package string `name:"package" short:"k" brief:"{CGenPbEntityBriefPackage}"` Package string `name:"package" short:"k" brief:"{CGenPbEntityBriefPackage}"`
GoPackage string `name:"goPackage" short:"g" brief:"{CGenPbEntityBriefGoPackage}"` GoPackage string `name:"goPackage" short:"g" brief:"{CGenPbEntityBriefGoPackage}"`
Link string `name:"link" short:"l" brief:"{CGenPbEntityBriefLink}"` Link string `name:"link" short:"l" brief:"{CGenPbEntityBriefLink}"`
Tables string `name:"tables" short:"t" brief:"{CGenPbEntityBriefTables}"` Tables string `name:"tables" short:"t" brief:"{CGenPbEntityBriefTables}"`
Prefix string `name:"prefix" short:"f" brief:"{CGenPbEntityBriefPrefix}"` Prefix string `name:"prefix" short:"f" brief:"{CGenPbEntityBriefPrefix}"`
RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenPbEntityBriefRemovePrefix}"` RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenPbEntityBriefRemovePrefix}"`
RemoveFieldPrefix string `name:"removeFieldPrefix" short:"rf" brief:"{CGenPbEntityBriefRemoveFieldPrefix}"` RemoveFieldPrefix string `name:"removeFieldPrefix" short:"rf" brief:"{CGenPbEntityBriefRemoveFieldPrefix}"`
TablesEx string `name:"tablesEx" short:"x" brief:"{CGenDaoBriefTablesEx}"` TablesEx string `name:"tablesEx" short:"x" brief:"{CGenDaoBriefTablesEx}"`
NameCase string `name:"nameCase" short:"n" brief:"{CGenPbEntityBriefNameCase}" d:"Camel"` NameCase string `name:"nameCase" short:"n" brief:"{CGenPbEntityBriefNameCase}" d:"Camel"`
JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"none"` JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"none"`
Option string `name:"option" short:"o" brief:"{CGenPbEntityBriefOption}"` Option string `name:"option" short:"o" brief:"{CGenPbEntityBriefOption}"`
ShardingPattern []string `name:"shardingPattern" short:"sp" brief:"{CGenDaoBriefShardingPattern}"`
TypeMapping map[DBFieldTypeName]CustomAttributeType `name:"typeMapping" short:"y" brief:"{CGenPbEntityBriefTypeMapping}" orphan:"true"` TypeMapping map[DBFieldTypeName]CustomAttributeType `name:"typeMapping" short:"y" brief:"{CGenPbEntityBriefTypeMapping}" orphan:"true"`
FieldMapping map[DBTableFieldName]CustomAttributeType `name:"fieldMapping" short:"fm" brief:"{CGenPbEntityBriefFieldMapping}" orphan:"true"` FieldMapping map[DBTableFieldName]CustomAttributeType `name:"fieldMapping" short:"fm" brief:"{CGenPbEntityBriefFieldMapping}" orphan:"true"`
@ -122,6 +125,7 @@ CONFIGURATION SUPPORT
CGenPbEntityBriefTablesEx = `generate all models exclude the specified tables, multiple prefix separated with ','` CGenPbEntityBriefTablesEx = `generate all models exclude the specified tables, multiple prefix separated with ','`
CGenPbEntityBriefRemoveFieldPrefix = `remove specified prefix of the field, multiple prefix separated with ','` CGenPbEntityBriefRemoveFieldPrefix = `remove specified prefix of the field, multiple prefix separated with ','`
CGenPbEntityBriefOption = `extra protobuf options` CGenPbEntityBriefOption = `extra protobuf options`
CGenPbEntityBriefShardingPattern = `sharding pattern for table name, e.g. "users_?" will replace tables "users_001,users_002,..." to "users" pbentity`
CGenPbEntityBriefGroup = ` CGenPbEntityBriefGroup = `
specifying the configuration group name of database for generated ORM instance, specifying the configuration group name of database for generated ORM instance,
it's not necessary and the default value is "default" it's not necessary and the default value is "default"
@ -252,6 +256,7 @@ func init() {
`CGenPbEntityBriefNameCase`: CGenPbEntityBriefNameCase, `CGenPbEntityBriefNameCase`: CGenPbEntityBriefNameCase,
`CGenPbEntityBriefJsonCase`: CGenPbEntityBriefJsonCase, `CGenPbEntityBriefJsonCase`: CGenPbEntityBriefJsonCase,
`CGenPbEntityBriefOption`: CGenPbEntityBriefOption, `CGenPbEntityBriefOption`: CGenPbEntityBriefOption,
`CGenPbEntityBriefShardingPattern`: CGenPbEntityBriefShardingPattern,
`CGenPbEntityBriefTypeMapping`: CGenPbEntityBriefTypeMapping, `CGenPbEntityBriefTypeMapping`: CGenPbEntityBriefTypeMapping,
`CGenPbEntityBriefFieldMapping`: CGenPbEntityBriefFieldMapping, `CGenPbEntityBriefFieldMapping`: CGenPbEntityBriefFieldMapping,
}) })
@ -321,6 +326,7 @@ func doGenPbEntityForArray(ctx context.Context, index int, in CGenPbEntityInput)
} }
tableNames := ([]string)(nil) tableNames := ([]string)(nil)
shardingNewTableSet := gset.NewStrSet()
if in.Tables != "" { if in.Tables != "" {
tableNames = gstr.SplitAndTrim(in.Tables, ",") tableNames = gstr.SplitAndTrim(in.Tables, ",")
} else { } else {
@ -348,6 +354,31 @@ func doGenPbEntityForArray(ctx context.Context, index int, in CGenPbEntityInput)
for _, v := range removePrefixArray { for _, v := range removePrefixArray {
newTableName = gstr.TrimLeftStr(newTableName, v, 1) newTableName = gstr.TrimLeftStr(newTableName, v, 1)
} }
var shardingTableName string
if len(in.ShardingPattern) > 0 {
for _, pattern := range in.ShardingPattern {
var (
match []string
regPattern = gstr.Replace(pattern, "?", `(.+)`)
)
match, err = gregex.MatchString(regPattern, newTableName)
if err != nil {
mlog.Fatalf(`invalid sharding pattern "%s": %+v`, pattern, err)
}
if len(match) < 2 {
continue
}
shardingTableName = gstr.Replace(pattern, "?", "")
shardingTableName = gstr.Trim(shardingTableName, `_.-`)
}
}
if shardingTableName != "" {
if shardingNewTableSet.Contains(shardingTableName) {
continue
}
shardingNewTableSet.Add(shardingTableName)
newTableName = shardingTableName
}
generatePbEntityContentFile(ctx, CGenPbEntityInternalInput{ generatePbEntityContentFile(ctx, CGenPbEntityInternalInput{
CGenPbEntityInput: in, CGenPbEntityInput: in,
DB: db, DB: db,
@ -414,13 +445,22 @@ func generateEntityMessageDefinition(entityName string, fieldMap map[string]*gdb
appendImports = append(appendImports, imports) appendImports = append(appendImports, imports)
} }
} }
tw := tablewriter.NewWriter(buffer) table := tablewriter.NewTable(buffer,
tw.SetBorder(false) tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
tw.SetRowLine(false) Borders: tw.Border{Top: tw.Off, Bottom: tw.Off, Left: tw.On, Right: tw.Off},
tw.SetAutoWrapText(false) Settings: tw.Settings{
tw.SetColumnSeparator("") Separators: tw.Separators{BetweenRows: tw.Off, BetweenColumns: tw.Off},
tw.AppendBulk(array) },
tw.Render() Symbols: tw.NewSymbolCustom("Proto").WithColumn(" "),
})),
tablewriter.WithConfig(tablewriter.Config{
Row: tw.CellConfig{
Formatting: tw.CellFormatting{AutoWrap: tw.WrapNone},
},
}),
)
table.Bulk(array)
table.Render()
stContent := buffer.String() stContent := buffer.String()
// Let's do this hack of table writer for indent! // Let's do this hack of table writer for indent!
stContent = regexp.MustCompile(`\s+\n`).ReplaceAllString(gstr.Replace(stContent, " #", ""), "\n") stContent = regexp.MustCompile(`\s+\n`).ReplaceAllString(gstr.Replace(stContent, " #", ""), "\n")
@ -441,14 +481,23 @@ func generateMessageFieldForPbEntity(index int, field *gdb.TableField, in CGenPb
err error err error
ctx = gctx.GetInitCtx() ctx = gctx.GetInitCtx()
) )
if in.TypeMapping != nil && len(in.TypeMapping) > 0 { if in.TypeMapping != nil && len(in.TypeMapping) > 0 {
// match typeMapping after local type transform.
// eg: double => string, varchar => string etc.
localTypeName, err = in.DB.CheckLocalTypeForField(ctx, field.Type, nil) localTypeName, err = in.DB.CheckLocalTypeForField(ctx, field.Type, nil)
if err != nil { if err != nil {
panic(err) panic(err)
} }
if localTypeName != "" { if localTypeName != "" {
if typeMapping, ok := in.TypeMapping[strings.ToLower(string(localTypeName))]; ok { if typeMappingLocal, localOk := in.TypeMapping[strings.ToLower(string(localTypeName))]; localOk {
localTypeNameStr = typeMappingLocal.Type
appendImport = typeMappingLocal.Import
}
}
// Try match unknown / string localTypeName with db type.
if localTypeName == "" || localTypeName == gdb.LocalTypeString {
formattedFieldType, _ := in.DB.GetFormattedDBTypeNameForField(field.Type)
if typeMapping, ok := in.TypeMapping[strings.ToLower(formattedFieldType)]; ok {
localTypeNameStr = typeMapping.Type localTypeNameStr = typeMapping.Type
appendImport = typeMapping.Import appendImport = typeMapping.Import
} }

View File

@ -13,8 +13,6 @@ import (
"sync" "sync"
"sync/atomic" "sync/atomic"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
"github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/container/gset"
@ -25,6 +23,9 @@ import (
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gtag" "github.com/gogf/gf/v2/util/gtag"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
) )
const ( const (

View File

@ -33,7 +33,7 @@ func (c CGenService) generateType(generatedContent *bytes.Buffer, srcStructFunct
generatedContent.WriteString("type(") generatedContent.WriteString("type(")
generatedContent.WriteString("\n") generatedContent.WriteString("\n")
srcStructFunctions.Iterator(func(key, value interface{}) bool { srcStructFunctions.Iterator(func(key, value any) bool {
var ( var (
funcContents = make([]string, 0) funcContents = make([]string, 0)
funcContent string funcContent string
@ -71,7 +71,7 @@ func (c CGenService) generateVar(generatedContent *bytes.Buffer, srcStructFuncti
// Generating variable and register definitions. // Generating variable and register definitions.
var variableContent string var variableContent string
srcStructFunctions.Iterator(func(key, value interface{}) bool { srcStructFunctions.Iterator(func(key, value any) bool {
structName := key.(string) structName := key.(string)
variableContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentVariable, g.MapStrStr{ variableContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentVariable, g.MapStrStr{
"{StructName}": structName, "{StructName}": structName,
@ -93,7 +93,7 @@ func (c CGenService) generateVar(generatedContent *bytes.Buffer, srcStructFuncti
// See: const.TemplateGenServiceContentRegister // See: const.TemplateGenServiceContentRegister
func (c CGenService) generateFunc(generatedContent *bytes.Buffer, srcStructFunctions *gmap.ListMap) { func (c CGenService) generateFunc(generatedContent *bytes.Buffer, srcStructFunctions *gmap.ListMap) {
// Variable register function definitions. // Variable register function definitions.
srcStructFunctions.Iterator(func(key, value interface{}) bool { srcStructFunctions.Iterator(func(key, value any) bool {
structName := key.(string) structName := key.(string)
generatedContent.WriteString(gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentRegister, g.MapStrStr{ generatedContent.WriteString(gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentRegister, g.MapStrStr{
"{StructName}": structName, "{StructName}": structName,

View File

@ -1,12 +1,12 @@
module github.com/gogf/gf/cmd/gf/cmd/gf/testdata/vardump/v2 module github.com/gogf/gf/cmd/gf/cmd/gf/testdata/vardump/v2
go 1.18 go 1.22
require github.com/gogf/gf/v2 v2.8.2 require github.com/gogf/gf/v2 v2.8.2
require ( require (
go.opentelemetry.io/otel v1.24.0 // indirect go.opentelemetry.io/otel v1.32.0 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect go.opentelemetry.io/otel/trace v1.32.0 // indirect
) )
replace github.com/gogf/gf/v2 => ../../../../../../../ replace github.com/gogf/gf/v2 => ../../../../../../../

View File

@ -19,10 +19,12 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg=
go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI= go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI=
go.opentelemetry.io/otel/sdk v1.24.0 h1:YMPPDNymmQN3ZgczicBY3B6sf9n62Dlj9pWD3ucgoDw= go.opentelemetry.io/otel/sdk v1.24.0 h1:YMPPDNymmQN3ZgczicBY3B6sf9n62Dlj9pWD3ucgoDw=
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8=
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=

View File

@ -12,11 +12,11 @@ import (
// TableUser is the golang structure of table table_user for DAO operations like Where/Data. // TableUser is the golang structure of table table_user for DAO operations like Where/Data.
type TableUser struct { type TableUser struct {
g.Meta `orm:"table:table_user, do:true"` g.Meta `orm:"table:table_user, do:true"`
Id interface{} // User ID Id any // User ID
Passport interface{} // User Passport Passport any // User Passport
Password interface{} // User Password Password any // User Password
Nickname interface{} // User Nickname Nickname any // User Nickname
Score interface{} // Total score amount. Score any // Total score amount.
CreateAt *gtime.Time // Created Time CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time UpdateAt *gtime.Time // Updated Time
} }

View File

@ -12,11 +12,11 @@ import (
// TableUser is the golang structure of table table_user for DAO operations like Where/Data. // TableUser is the golang structure of table table_user for DAO operations like Where/Data.
type TableUser struct { type TableUser struct {
g.Meta `orm:"table:table_user, do:true"` g.Meta `orm:"table:table_user, do:true"`
Id interface{} // User ID Id any // User ID
Passport interface{} // User Passport Passport any // User Passport
Password interface{} // User Password Password any // User Password
Nickname interface{} // User Nickname Nickname any // User Nickname
Score interface{} // Total score amount. Score any // Total score amount.
CreateAt *gtime.Time // Created Time CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time UpdateAt *gtime.Time // Updated Time
} }

View File

@ -12,10 +12,10 @@ import (
// TableUser is the golang structure of table table_user for DAO operations like Where/Data. // TableUser is the golang structure of table table_user for DAO operations like Where/Data.
type TableUser struct { type TableUser struct {
g.Meta `orm:"table:table_user, do:true"` g.Meta `orm:"table:table_user, do:true"`
Id interface{} // Id any //
Passport interface{} // Passport any //
Password interface{} // Password any //
Nickname interface{} // Nickname any //
CreatedAt *gtime.Time // CreatedAt *gtime.Time //
UpdatedAt *gtime.Time // UpdatedAt *gtime.Time //
} }

View File

@ -12,11 +12,11 @@ import (
// TableUser is the golang structure of table table_user for DAO operations like Where/Data. // TableUser is the golang structure of table table_user for DAO operations like Where/Data.
type TableUser struct { type TableUser struct {
g.Meta `orm:"table:table_user, do:true"` g.Meta `orm:"table:table_user, do:true"`
Id interface{} // User ID Id any // User ID
Passport interface{} // User Passport Passport any // User Passport
Password interface{} // User Password Password any // User Password
Nickname interface{} // User Nickname Nickname any // User Nickname
Score interface{} // Total score amount. Score any // Total score amount.
CreateAt *gtime.Time // Created Time CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time UpdateAt *gtime.Time // Updated Time
} }

View File

@ -1,44 +1,54 @@
CREATE TABLE `single_table` ( CREATE TABLE `single_table`
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID', (
`passport` varchar(45) NOT NULL COMMENT 'User Passport', `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`password` varchar(45) NOT NULL COMMENT 'User Password', `passport` varchar(45) NOT NULL COMMENT 'User Passport',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname', `password` varchar(45) NOT NULL COMMENT 'User Password',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.', `nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`score` decimal(10, 2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time', `create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time', `update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users_0001` ( CREATE TABLE `users_0001`
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID', (
`passport` varchar(45) NOT NULL COMMENT 'User Passport', `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`password` varchar(45) NOT NULL COMMENT 'User Password', `passport` varchar(45) NOT NULL COMMENT 'User Passport',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname', `password` varchar(45) NOT NULL COMMENT 'User Password',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.', `nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`score` decimal(10, 2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time', `create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time', `update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users_0002` ( CREATE TABLE `users_0002`
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID', (
`passport` varchar(45) NOT NULL COMMENT 'User Passport', `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`password` varchar(45) NOT NULL COMMENT 'User Password', `passport` varchar(45) NOT NULL COMMENT 'User Passport',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname', `password` varchar(45) NOT NULL COMMENT 'User Password',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.', `nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`score` decimal(10, 2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time', `create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time', `update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users_0003` ( CREATE TABLE `orders_0001`
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID', (
`passport` varchar(45) NOT NULL COMMENT 'User Passport', `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'ORDER ID',
`password` varchar(45) NOT NULL COMMENT 'User Password', `amount` decimal(10, 2) unsigned DEFAULT NULL COMMENT 'Total amount.',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname', `create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.', `update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `orders_0002`
(
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'ORDER ID',
`amount` decimal(10, 2) unsigned DEFAULT NULL COMMENT 'Total amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time', `create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time', `update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)

View File

@ -63,14 +63,14 @@ func (s *sArticle) T3(ctx context.Context, b *gdbas.Model) (c, d *gdbas.Model, e
* random comment * random comment
*/ */
// func (s *sArticle) T4(i interface{}) interface{} // func (s *sArticle) T4(i any) any
// # $ % ^ & * ( ) _ + - = { } | [ ] \ : " ; ' < > ? , . / // # $ % ^ & * ( ) _ + - = { } | [ ] \ : " ; ' < > ? , . /
func (s *sArticle) T4(i interface{}) interface{} { func (s *sArticle) T4(i any) any {
return nil return nil
} }
/** /**
* func (s *sArticle) T4(i interface{}) interface{} { * func (s *sArticle) T4(i any) any {
* return nil * return nil
* } * }
*/ */

View File

@ -36,9 +36,9 @@ type (
* @author oldme * @author oldme
*/ */
T3(ctx context.Context, b *gdbas.Model) (c *gdbas.Model, d *gdbas.Model, err error) T3(ctx context.Context, b *gdbas.Model) (c *gdbas.Model, d *gdbas.Model, err error)
// func (s *sArticle) T4(i interface{}) interface{} // func (s *sArticle) T4(i any) any
// # $ % ^ & * ( ) _ + - = { } | [ ] \ : " ; ' < > ? , . / // # $ % ^ & * ( ) _ + - = { } | [ ] \ : " ; ' < > ? , . /
T4(i interface{}) interface{} T4(i any) any
} }
) )

View File

@ -12,11 +12,11 @@ import (
// User1 is the golang structure of table user1 for DAO operations like Where/Data. // User1 is the golang structure of table user1 for DAO operations like Where/Data.
type User1 struct { type User1 struct {
g.Meta `orm:"table:user1, do:true"` g.Meta `orm:"table:user1, do:true"`
Id interface{} // User ID Id any // User ID
Passport interface{} // User Passport Passport any // User Passport
Password interface{} // User Password Password any // User Password
Nickname interface{} // User Nickname Nickname any // User Nickname
Score interface{} // Total score amount. Score any // Total score amount.
CreateAt *gtime.Time // Created Time CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time UpdateAt *gtime.Time // Updated Time
} }

View File

@ -12,11 +12,11 @@ import (
// User2 is the golang structure of table user2 for DAO operations like Where/Data. // User2 is the golang structure of table user2 for DAO operations like Where/Data.
type User2 struct { type User2 struct {
g.Meta `orm:"table:user2, do:true"` g.Meta `orm:"table:user2, do:true"`
Id interface{} // User ID Id any // User ID
Passport interface{} // User Passport Passport any // User Passport
Password interface{} // User Password Password any // User Password
Nickname interface{} // User Nickname Nickname any // User Nickname
Score interface{} // Total score amount. Score any // Total score amount.
CreateAt *gtime.Time // Created Time CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time UpdateAt *gtime.Time // Updated Time
} }

View File

@ -12,11 +12,11 @@ import (
// User1 is the golang structure of table user1 for DAO operations like Where/Data. // User1 is the golang structure of table user1 for DAO operations like Where/Data.
type User1 struct { type User1 struct {
g.Meta `orm:"table:user1, do:true"` g.Meta `orm:"table:user1, do:true"`
Id interface{} // User ID Id any // User ID
Passport interface{} // User Passport Passport any // User Passport
Password interface{} // User Password Password any // User Password
Nickname interface{} // User Nickname Nickname any // User Nickname
Score interface{} // Total score amount. Score any // Total score amount.
CreateAt *gtime.Time // Created Time CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time UpdateAt *gtime.Time // Updated Time
} }

View File

@ -12,11 +12,11 @@ import (
// User2 is the golang structure of table user2 for DAO operations like Where/Data. // User2 is the golang structure of table user2 for DAO operations like Where/Data.
type User2 struct { type User2 struct {
g.Meta `orm:"table:user2, do:true"` g.Meta `orm:"table:user2, do:true"`
Id interface{} // User ID Id any // User ID
Passport interface{} // User Passport Passport any // User Passport
Password interface{} // User Password Password any // User Password
Nickname interface{} // User Nickname Nickname any // User Nickname
Score interface{} // Total score amount. Score any // Total score amount.
CreateAt *gtime.Time // Created Time CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time UpdateAt *gtime.Time // Updated Time
} }

View File

@ -12,11 +12,11 @@ import (
// TableUser is the golang structure of table table_user for DAO operations like Where/Data. // TableUser is the golang structure of table table_user for DAO operations like Where/Data.
type TableUser struct { type TableUser struct {
g.Meta `orm:"table:table_user, do:true"` g.Meta `orm:"table:table_user, do:true"`
Id interface{} // User ID Id any // User ID
ParentId interface{} // ParentId any //
Passport interface{} // User Passport Passport any // User Passport
PassWord interface{} // User Password PassWord any // User Password
Nickname2 interface{} // User Nickname Nickname2 any // User Nickname
CreateAt *gtime.Time // Created Time CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time UpdateAt *gtime.Time // Updated Time
} }

View File

@ -0,0 +1,23 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
syntax = "proto3";
package pbentity;
option go_package = "github.com/gogf/gf/cmd/gf/v2/internal/cmd/api/pbentity";
import "google/protobuf/struct.proto";
import "google/protobuf/timestamp.proto";
message TableUser {
uint32 Id = 1; // User ID
string Passport = 2; // User Passport
string Password = 3; // User Password
string Nickname = 4; // User Nickname
double Score = 5; // Total score amount.
google.protobuf.Value Data = 6; // User Data
google.protobuf.Timestamp CreateAt = 7; // Created Time
google.protobuf.Timestamp UpdateAt = 8; // Updated Time
}

View File

@ -0,0 +1,23 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
syntax = "proto3";
package pbentity;
option go_package = "github.com/gogf/gf/cmd/gf/v2/internal/cmd/api/pbentity";
import "google/protobuf/struct.proto";
import "google/protobuf/timestamp.proto";
message TableUser {
uint32 Id = 1; // User ID
string Passport = 2; // User Passport
string Password = 3; // User Password
string Nickname = 4; // User Nickname
string Score = 5; // Total score amount.
google.protobuf.Value Data = 6; // User Data
google.protobuf.Timestamp CreateAt = 7; // Created Time
google.protobuf.Timestamp UpdateAt = 8; // Updated Time
}

View File

@ -27,7 +27,7 @@ var (
// {{.TplTableNameCamelCase}} is a globally accessible object for table {{.TplTableName}} operations. // {{.TplTableNameCamelCase}} is a globally accessible object for table {{.TplTableName}} operations.
{{.TplTableNameCamelCase}} = {{.TplTableNameCamelLowerCase}}Dao{ {{.TplTableNameCamelCase}} = {{.TplTableNameCamelLowerCase}}Dao{
{{- if .TplTableSharding -}} {{- if .TplTableSharding -}}
internal.New{{.TplTableNameCamelCase}}Dao(userShardingHandler), internal.New{{.TplTableNameCamelCase}}Dao({{.TplTableNameCamelLowerCase}}ShardingHandler),
{{- else -}} {{- else -}}
internal.New{{.TplTableNameCamelCase}}Dao(), internal.New{{.TplTableNameCamelCase}}Dao(),
{{- end -}} {{- end -}}
@ -35,13 +35,13 @@ var (
) )
{{if .TplTableSharding -}} {{if .TplTableSharding -}}
// userShardingHandler is the handler for sharding operations. // {{.TplTableNameCamelLowerCase}}ShardingHandler is the handler for sharding operations.
// You can fill this sharding handler with your custom implementation. // You can fill this sharding handler with your custom implementation.
func userShardingHandler(m *gdb.Model) *gdb.Model { func {{.TplTableNameCamelLowerCase}}ShardingHandler(m *gdb.Model) *gdb.Model {
m = m.Sharding(gdb.ShardingConfig{ m = m.Sharding(gdb.ShardingConfig{
Table: gdb.ShardingTableConfig{ Table: gdb.ShardingTableConfig{
Enable: true, Enable: true,
Prefix: "", Prefix: "{{.TplTableShardingPrefix}}",
// Replace Rule field with your custom sharding rule. // Replace Rule field with your custom sharding rule.
// Or you can use "&gdb.DefaultShardingRule{}" for default sharding rule. // Or you can use "&gdb.DefaultShardingRule{}" for default sharding rule.
Rule: nil, Rule: nil,

View File

@ -162,8 +162,14 @@ func (s serviceInstall) getGoPathBin() string {
func (s serviceInstall) getAvailablePaths() []serviceInstallAvailablePath { func (s serviceInstall) getAvailablePaths() []serviceInstallAvailablePath {
var ( var (
folderPaths []serviceInstallAvailablePath folderPaths []serviceInstallAvailablePath
binaryFileName = "gf" + gfile.Ext(gfile.SelfPath()) binaryFileName = "gf"
) )
// Windows binary file name suffix.
if runtime.GOOS == "windows" {
binaryFileName += ".exe"
}
// $GOPATH/bin // $GOPATH/bin
if goPathBin := s.getGoPathBin(); goPathBin != "" { if goPathBin := s.getGoPathBin(); goPathBin != "" {
folderPaths = s.checkAndAppendToAvailablePath( folderPaths = s.checkAndAppendToAvailablePath(

View File

@ -51,26 +51,26 @@ func SetHeaderPrint(enabled bool) {
} }
} }
func Print(v ...interface{}) { func Print(v ...any) {
logger.Print(ctx, v...) logger.Print(ctx, v...)
} }
func Printf(format string, v ...interface{}) { func Printf(format string, v ...any) {
logger.Printf(ctx, format, v...) logger.Printf(ctx, format, v...)
} }
func Fatal(v ...interface{}) { func Fatal(v ...any) {
logger.Fatal(ctx, v...) logger.Fatal(ctx, v...)
} }
func Fatalf(format string, v ...interface{}) { func Fatalf(format string, v ...any) {
logger.Fatalf(ctx, format, v...) logger.Fatalf(ctx, format, v...)
} }
func Debug(v ...interface{}) { func Debug(v ...any) {
logger.Debug(ctx, v...) logger.Debug(ctx, v...)
} }
func Debugf(format string, v ...interface{}) { func Debugf(format string, v ...any) {
logger.Debugf(ctx, format, v...) logger.Debugf(ctx, format, v...)
} }

View File

@ -12,12 +12,13 @@ import (
"golang.org/x/tools/imports" "golang.org/x/tools/imports"
"github.com/gogf/gf/cmd/gf/v2/internal/consts"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/os/gproc"
"github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/cmd/gf/v2/internal/consts"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
) )
// GoFmt formats the source file and adds or removes import statements as necessary. // GoFmt formats the source file and adds or removes import statements as necessary.

View File

@ -7,6 +7,8 @@
package main package main
import ( import (
_ "time/tzdata"
"github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gctx"

View File

@ -28,7 +28,7 @@ import (
// when its initialization and cannot be changed then. // when its initialization and cannot be changed then.
type Array struct { type Array struct {
mu rwmutex.RWMutex mu rwmutex.RWMutex
array []interface{} array []any
} }
// New creates and returns an empty array. // New creates and returns an empty array.
@ -49,7 +49,7 @@ func NewArray(safe ...bool) *Array {
func NewArraySize(size int, cap int, safe ...bool) *Array { func NewArraySize(size int, cap int, safe ...bool) *Array {
return &Array{ return &Array{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
array: make([]interface{}, size, cap), array: make([]any, size, cap),
} }
} }
@ -59,7 +59,7 @@ func NewArrayRange(start, end, step int, safe ...bool) *Array {
if step == 0 { if step == 0 {
panic(fmt.Sprintf(`invalid step value: %d`, step)) panic(fmt.Sprintf(`invalid step value: %d`, step))
} }
slice := make([]interface{}, 0) slice := make([]any, 0)
index := 0 index := 0
for i := start; i <= end; i += step { for i := start; i <= end; i += step {
slice = append(slice, i) slice = append(slice, i)
@ -70,20 +70,20 @@ func NewArrayRange(start, end, step int, safe ...bool) *Array {
// NewFrom is alias of NewArrayFrom. // NewFrom is alias of NewArrayFrom.
// See NewArrayFrom. // See NewArrayFrom.
func NewFrom(array []interface{}, safe ...bool) *Array { func NewFrom(array []any, safe ...bool) *Array {
return NewArrayFrom(array, safe...) return NewArrayFrom(array, safe...)
} }
// NewFromCopy is alias of NewArrayFromCopy. // NewFromCopy is alias of NewArrayFromCopy.
// See NewArrayFromCopy. // See NewArrayFromCopy.
func NewFromCopy(array []interface{}, safe ...bool) *Array { func NewFromCopy(array []any, safe ...bool) *Array {
return NewArrayFromCopy(array, safe...) return NewArrayFromCopy(array, safe...)
} }
// NewArrayFrom creates and returns an array with given slice `array`. // NewArrayFrom creates and returns an array with given slice `array`.
// The parameter `safe` is used to specify whether using array in concurrent-safety, // The parameter `safe` is used to specify whether using array in concurrent-safety,
// which is false in default. // which is false in default.
func NewArrayFrom(array []interface{}, safe ...bool) *Array { func NewArrayFrom(array []any, safe ...bool) *Array {
return &Array{ return &Array{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
array: array, array: array,
@ -93,8 +93,8 @@ func NewArrayFrom(array []interface{}, safe ...bool) *Array {
// NewArrayFromCopy creates and returns an array from a copy of given slice `array`. // NewArrayFromCopy creates and returns an array from a copy of given slice `array`.
// The parameter `safe` is used to specify whether using array in concurrent-safety, // The parameter `safe` is used to specify whether using array in concurrent-safety,
// which is false in default. // which is false in default.
func NewArrayFromCopy(array []interface{}, safe ...bool) *Array { func NewArrayFromCopy(array []any, safe ...bool) *Array {
newArray := make([]interface{}, len(array)) newArray := make([]any, len(array))
copy(newArray, array) copy(newArray, array)
return &Array{ return &Array{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
@ -104,14 +104,14 @@ func NewArrayFromCopy(array []interface{}, safe ...bool) *Array {
// At returns the value by the specified index. // At returns the value by the specified index.
// If the given `index` is out of range of the array, it returns `nil`. // If the given `index` is out of range of the array, it returns `nil`.
func (a *Array) At(index int) (value interface{}) { func (a *Array) At(index int) (value any) {
value, _ = a.Get(index) value, _ = a.Get(index)
return return
} }
// Get returns the value by the specified index. // Get returns the value by the specified index.
// If the given `index` is out of range of the array, the `found` is false. // If the given `index` is out of range of the array, the `found` is false.
func (a *Array) Get(index int) (value interface{}, found bool) { func (a *Array) Get(index int) (value any, found bool) {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
if index < 0 || index >= len(a.array) { if index < 0 || index >= len(a.array) {
@ -121,7 +121,7 @@ func (a *Array) Get(index int) (value interface{}, found bool) {
} }
// Set sets value to specified index. // Set sets value to specified index.
func (a *Array) Set(index int, value interface{}) error { func (a *Array) Set(index int, value any) error {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if index < 0 || index >= len(a.array) { if index < 0 || index >= len(a.array) {
@ -132,7 +132,7 @@ func (a *Array) Set(index int, value interface{}) error {
} }
// SetArray sets the underlying slice array with the given `array`. // SetArray sets the underlying slice array with the given `array`.
func (a *Array) SetArray(array []interface{}) *Array { func (a *Array) SetArray(array []any) *Array {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
a.array = array a.array = array
@ -140,7 +140,7 @@ func (a *Array) SetArray(array []interface{}) *Array {
} }
// Replace replaces the array items by given `array` from the beginning of array. // Replace replaces the array items by given `array` from the beginning of array.
func (a *Array) Replace(array []interface{}) *Array { func (a *Array) Replace(array []any) *Array {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
max := len(array) max := len(array)
@ -164,7 +164,7 @@ func (a *Array) Sum() (sum int) {
} }
// SortFunc sorts the array by custom function `less`. // SortFunc sorts the array by custom function `less`.
func (a *Array) SortFunc(less func(v1, v2 interface{}) bool) *Array { func (a *Array) SortFunc(less func(v1, v2 any) bool) *Array {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
sort.Slice(a.array, func(i, j int) bool { sort.Slice(a.array, func(i, j int) bool {
@ -174,26 +174,26 @@ func (a *Array) SortFunc(less func(v1, v2 interface{}) bool) *Array {
} }
// InsertBefore inserts the `values` to the front of `index`. // InsertBefore inserts the `values` to the front of `index`.
func (a *Array) InsertBefore(index int, values ...interface{}) error { func (a *Array) InsertBefore(index int, values ...any) error {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if index < 0 || index >= len(a.array) { if index < 0 || index >= len(a.array) {
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
} }
rear := append([]interface{}{}, a.array[index:]...) rear := append([]any{}, a.array[index:]...)
a.array = append(a.array[0:index], values...) a.array = append(a.array[0:index], values...)
a.array = append(a.array, rear...) a.array = append(a.array, rear...)
return nil return nil
} }
// InsertAfter inserts the `values` to the back of `index`. // InsertAfter inserts the `values` to the back of `index`.
func (a *Array) InsertAfter(index int, values ...interface{}) error { func (a *Array) InsertAfter(index int, values ...any) error {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if index < 0 || index >= len(a.array) { if index < 0 || index >= len(a.array) {
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
} }
rear := append([]interface{}{}, a.array[index+1:]...) rear := append([]any{}, a.array[index+1:]...)
a.array = append(a.array[0:index+1], values...) a.array = append(a.array[0:index+1], values...)
a.array = append(a.array, rear...) a.array = append(a.array, rear...)
return nil return nil
@ -201,14 +201,14 @@ func (a *Array) InsertAfter(index int, values ...interface{}) error {
// Remove removes an item by index. // Remove removes an item by index.
// If the given `index` is out of range of the array, the `found` is false. // If the given `index` is out of range of the array, the `found` is false.
func (a *Array) Remove(index int) (value interface{}, found bool) { func (a *Array) Remove(index int) (value any, found bool) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
return a.doRemoveWithoutLock(index) return a.doRemoveWithoutLock(index)
} }
// doRemoveWithoutLock removes an item by index without lock. // doRemoveWithoutLock removes an item by index without lock.
func (a *Array) doRemoveWithoutLock(index int) (value interface{}, found bool) { func (a *Array) doRemoveWithoutLock(index int) (value any, found bool) {
if index < 0 || index >= len(a.array) { if index < 0 || index >= len(a.array) {
return nil, false return nil, false
} }
@ -232,7 +232,7 @@ func (a *Array) doRemoveWithoutLock(index int) (value interface{}, found bool) {
// RemoveValue removes an item by value. // RemoveValue removes an item by value.
// It returns true if value is found in the array, or else false if not found. // It returns true if value is found in the array, or else false if not found.
func (a *Array) RemoveValue(value interface{}) bool { func (a *Array) RemoveValue(value any) bool {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if i := a.doSearchWithoutLock(value); i != -1 { if i := a.doSearchWithoutLock(value); i != -1 {
@ -243,7 +243,7 @@ func (a *Array) RemoveValue(value interface{}) bool {
} }
// RemoveValues removes multiple items by `values`. // RemoveValues removes multiple items by `values`.
func (a *Array) RemoveValues(values ...interface{}) { func (a *Array) RemoveValues(values ...any) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
for _, value := range values { for _, value := range values {
@ -254,7 +254,7 @@ func (a *Array) RemoveValues(values ...interface{}) {
} }
// PushLeft pushes one or multiple items to the beginning of array. // PushLeft pushes one or multiple items to the beginning of array.
func (a *Array) PushLeft(value ...interface{}) *Array { func (a *Array) PushLeft(value ...any) *Array {
a.mu.Lock() a.mu.Lock()
a.array = append(value, a.array...) a.array = append(value, a.array...)
a.mu.Unlock() a.mu.Unlock()
@ -263,7 +263,7 @@ func (a *Array) PushLeft(value ...interface{}) *Array {
// PushRight pushes one or multiple items to the end of array. // PushRight pushes one or multiple items to the end of array.
// It equals to Append. // It equals to Append.
func (a *Array) PushRight(value ...interface{}) *Array { func (a *Array) PushRight(value ...any) *Array {
a.mu.Lock() a.mu.Lock()
a.array = append(a.array, value...) a.array = append(a.array, value...)
a.mu.Unlock() a.mu.Unlock()
@ -272,14 +272,14 @@ func (a *Array) PushRight(value ...interface{}) *Array {
// PopRand randomly pops and return an item out of array. // PopRand randomly pops and return an item out of array.
// Note that if the array is empty, the `found` is false. // Note that if the array is empty, the `found` is false.
func (a *Array) PopRand() (value interface{}, found bool) { func (a *Array) PopRand() (value any, found bool) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
return a.doRemoveWithoutLock(grand.Intn(len(a.array))) return a.doRemoveWithoutLock(grand.Intn(len(a.array)))
} }
// PopRands randomly pops and returns `size` items out of array. // PopRands randomly pops and returns `size` items out of array.
func (a *Array) PopRands(size int) []interface{} { func (a *Array) PopRands(size int) []any {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if size <= 0 || len(a.array) == 0 { if size <= 0 || len(a.array) == 0 {
@ -288,7 +288,7 @@ func (a *Array) PopRands(size int) []interface{} {
if size >= len(a.array) { if size >= len(a.array) {
size = len(a.array) size = len(a.array)
} }
array := make([]interface{}, size) array := make([]any, size)
for i := 0; i < size; i++ { for i := 0; i < size; i++ {
array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array))) array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array)))
} }
@ -297,7 +297,7 @@ func (a *Array) PopRands(size int) []interface{} {
// PopLeft pops and returns an item from the beginning of array. // PopLeft pops and returns an item from the beginning of array.
// Note that if the array is empty, the `found` is false. // Note that if the array is empty, the `found` is false.
func (a *Array) PopLeft() (value interface{}, found bool) { func (a *Array) PopLeft() (value any, found bool) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if len(a.array) == 0 { if len(a.array) == 0 {
@ -310,7 +310,7 @@ func (a *Array) PopLeft() (value interface{}, found bool) {
// PopRight pops and returns an item from the end of array. // PopRight pops and returns an item from the end of array.
// Note that if the array is empty, the `found` is false. // Note that if the array is empty, the `found` is false.
func (a *Array) PopRight() (value interface{}, found bool) { func (a *Array) PopRight() (value any, found bool) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
index := len(a.array) - 1 index := len(a.array) - 1
@ -323,7 +323,7 @@ func (a *Array) PopRight() (value interface{}, found bool) {
} }
// PopLefts pops and returns `size` items from the beginning of array. // PopLefts pops and returns `size` items from the beginning of array.
func (a *Array) PopLefts(size int) []interface{} { func (a *Array) PopLefts(size int) []any {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if size <= 0 || len(a.array) == 0 { if size <= 0 || len(a.array) == 0 {
@ -340,7 +340,7 @@ func (a *Array) PopLefts(size int) []interface{} {
} }
// PopRights pops and returns `size` items from the end of array. // PopRights pops and returns `size` items from the end of array.
func (a *Array) PopRights(size int) []interface{} { func (a *Array) PopRights(size int) []any {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if size <= 0 || len(a.array) == 0 { if size <= 0 || len(a.array) == 0 {
@ -364,7 +364,7 @@ func (a *Array) PopRights(size int) []interface{} {
// If `end` is negative, then the offset will start from the end of array. // If `end` is negative, then the offset will start from the end of array.
// If `end` is omitted, then the sequence will have everything from start up // If `end` is omitted, then the sequence will have everything from start up
// until the end of the array. // until the end of the array.
func (a *Array) Range(start int, end ...int) []interface{} { func (a *Array) Range(start int, end ...int) []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
offsetEnd := len(a.array) offsetEnd := len(a.array)
@ -377,9 +377,9 @@ func (a *Array) Range(start int, end ...int) []interface{} {
if start < 0 { if start < 0 {
start = 0 start = 0
} }
array := ([]interface{})(nil) array := ([]any)(nil)
if a.mu.IsSafe() { if a.mu.IsSafe() {
array = make([]interface{}, offsetEnd-start) array = make([]any, offsetEnd-start)
copy(array, a.array[start:offsetEnd]) copy(array, a.array[start:offsetEnd])
} else { } else {
array = a.array[start:offsetEnd] array = a.array[start:offsetEnd]
@ -400,7 +400,7 @@ func (a *Array) Range(start int, end ...int) []interface{} {
// If it is omitted, then the sequence will have everything from offset up until the end of the array. // If it is omitted, then the sequence will have everything from offset up until the end of the array.
// //
// Any possibility crossing the left border of array, it will fail. // Any possibility crossing the left border of array, it will fail.
func (a *Array) SubSlice(offset int, length ...int) []interface{} { func (a *Array) SubSlice(offset int, length ...int) []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
size := len(a.array) size := len(a.array)
@ -429,7 +429,7 @@ func (a *Array) SubSlice(offset int, length ...int) []interface{} {
size = len(a.array) - offset size = len(a.array) - offset
} }
if a.mu.IsSafe() { if a.mu.IsSafe() {
s := make([]interface{}, size) s := make([]any, size)
copy(s, a.array[offset:]) copy(s, a.array[offset:])
return s return s
} else { } else {
@ -438,7 +438,7 @@ func (a *Array) SubSlice(offset int, length ...int) []interface{} {
} }
// Append is alias of PushRight, please See PushRight. // Append is alias of PushRight, please See PushRight.
func (a *Array) Append(value ...interface{}) *Array { func (a *Array) Append(value ...any) *Array {
a.PushRight(value...) a.PushRight(value...)
return a return a
} }
@ -454,11 +454,11 @@ func (a *Array) Len() int {
// Slice returns the underlying data of array. // Slice returns the underlying data of array.
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
// or else a pointer to the underlying data. // or else a pointer to the underlying data.
func (a *Array) Slice() []interface{} { func (a *Array) Slice() []any {
if a.mu.IsSafe() { if a.mu.IsSafe() {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
array := make([]interface{}, len(a.array)) array := make([]any, len(a.array))
copy(array, a.array) copy(array, a.array)
return array return array
} else { } else {
@ -466,15 +466,15 @@ func (a *Array) Slice() []interface{} {
} }
} }
// Interfaces returns current array as []interface{}. // Interfaces returns current array as []any.
func (a *Array) Interfaces() []interface{} { func (a *Array) Interfaces() []any {
return a.Slice() return a.Slice()
} }
// Clone returns a new array, which is a copy of current array. // Clone returns a new array, which is a copy of current array.
func (a *Array) Clone() (newArray *Array) { func (a *Array) Clone() (newArray *Array) {
a.mu.RLock() a.mu.RLock()
array := make([]interface{}, len(a.array)) array := make([]any, len(a.array))
copy(array, a.array) copy(array, a.array)
a.mu.RUnlock() a.mu.RUnlock()
return NewArrayFrom(array, a.mu.IsSafe()) return NewArrayFrom(array, a.mu.IsSafe())
@ -484,26 +484,26 @@ func (a *Array) Clone() (newArray *Array) {
func (a *Array) Clear() *Array { func (a *Array) Clear() *Array {
a.mu.Lock() a.mu.Lock()
if len(a.array) > 0 { if len(a.array) > 0 {
a.array = make([]interface{}, 0) a.array = make([]any, 0)
} }
a.mu.Unlock() a.mu.Unlock()
return a return a
} }
// Contains checks whether a value exists in the array. // Contains checks whether a value exists in the array.
func (a *Array) Contains(value interface{}) bool { func (a *Array) Contains(value any) bool {
return a.Search(value) != -1 return a.Search(value) != -1
} }
// Search searches array by `value`, returns the index of `value`, // Search searches array by `value`, returns the index of `value`,
// or returns -1 if not exists. // or returns -1 if not exists.
func (a *Array) Search(value interface{}) int { func (a *Array) Search(value any) int {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
return a.doSearchWithoutLock(value) return a.doSearchWithoutLock(value)
} }
func (a *Array) doSearchWithoutLock(value interface{}) int { func (a *Array) doSearchWithoutLock(value any) int {
if len(a.array) == 0 { if len(a.array) == 0 {
return -1 return -1
} }
@ -527,9 +527,9 @@ func (a *Array) Unique() *Array {
} }
var ( var (
ok bool ok bool
temp interface{} temp any
uniqueSet = make(map[interface{}]struct{}) uniqueSet = make(map[any]struct{})
uniqueArray = make([]interface{}, 0, len(a.array)) uniqueArray = make([]any, 0, len(a.array))
) )
for i := 0; i < len(a.array); i++ { for i := 0; i < len(a.array); i++ {
temp = a.array[i] temp = a.array[i]
@ -544,7 +544,7 @@ func (a *Array) Unique() *Array {
} }
// LockFunc locks writing by callback function `f`. // LockFunc locks writing by callback function `f`.
func (a *Array) LockFunc(f func(array []interface{})) *Array { func (a *Array) LockFunc(f func(array []any)) *Array {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
f(a.array) f(a.array)
@ -552,7 +552,7 @@ func (a *Array) LockFunc(f func(array []interface{})) *Array {
} }
// RLockFunc locks reading by callback function `f`. // RLockFunc locks reading by callback function `f`.
func (a *Array) RLockFunc(f func(array []interface{})) *Array { func (a *Array) RLockFunc(f func(array []any)) *Array {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
f(a.array) f(a.array)
@ -563,13 +563,13 @@ func (a *Array) RLockFunc(f func(array []interface{})) *Array {
// The parameter `array` can be any garray or slice type. // The parameter `array` can be any garray or slice type.
// The difference between Merge and Append is Append supports only specified slice type, // The difference between Merge and Append is Append supports only specified slice type,
// but Merge supports more parameter types. // but Merge supports more parameter types.
func (a *Array) Merge(array interface{}) *Array { func (a *Array) Merge(array any) *Array {
return a.Append(gconv.Interfaces(array)...) return a.Append(gconv.Interfaces(array)...)
} }
// Fill fills an array with num entries of the value `value`, // Fill fills an array with num entries of the value `value`,
// keys starting at the `startIndex` parameter. // keys starting at the `startIndex` parameter.
func (a *Array) Fill(startIndex int, num int, value interface{}) error { func (a *Array) Fill(startIndex int, num int, value any) error {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if startIndex < 0 || startIndex > len(a.array) { if startIndex < 0 || startIndex > len(a.array) {
@ -588,7 +588,7 @@ func (a *Array) Fill(startIndex int, num int, value interface{}) error {
// Chunk splits an array into multiple arrays, // Chunk splits an array into multiple arrays,
// the size of each array is determined by `size`. // the size of each array is determined by `size`.
// The last chunk may contain less than size elements. // The last chunk may contain less than size elements.
func (a *Array) Chunk(size int) [][]interface{} { func (a *Array) Chunk(size int) [][]any {
if size < 1 { if size < 1 {
return nil return nil
} }
@ -596,7 +596,7 @@ func (a *Array) Chunk(size int) [][]interface{} {
defer a.mu.RUnlock() defer a.mu.RUnlock()
length := len(a.array) length := len(a.array)
chunks := int(math.Ceil(float64(length) / float64(size))) chunks := int(math.Ceil(float64(length) / float64(size)))
var n [][]interface{} var n [][]any
for i, end := 0, 0; chunks > 0; chunks-- { for i, end := 0, 0; chunks > 0; chunks-- {
end = (i + 1) * size end = (i + 1) * size
if end > length { if end > length {
@ -612,7 +612,7 @@ func (a *Array) Chunk(size int) [][]interface{} {
// If size is positive then the array is padded on the right, or negative on the left. // If size is positive then the array is padded on the right, or negative on the left.
// If the absolute value of `size` is less than or equal to the length of the array // If the absolute value of `size` is less than or equal to the length of the array
// then no padding takes place. // then no padding takes place.
func (a *Array) Pad(size int, val interface{}) *Array { func (a *Array) Pad(size int, val any) *Array {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if size == 0 || (size > 0 && size < len(a.array)) || (size < 0 && size > -len(a.array)) { if size == 0 || (size > 0 && size < len(a.array)) || (size < 0 && size > -len(a.array)) {
@ -623,7 +623,7 @@ func (a *Array) Pad(size int, val interface{}) *Array {
n = -size n = -size
} }
n -= len(a.array) n -= len(a.array)
tmp := make([]interface{}, n) tmp := make([]any, n)
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
tmp[i] = val tmp[i] = val
} }
@ -636,7 +636,7 @@ func (a *Array) Pad(size int, val interface{}) *Array {
} }
// Rand randomly returns one item from array(no deleting). // Rand randomly returns one item from array(no deleting).
func (a *Array) Rand() (value interface{}, found bool) { func (a *Array) Rand() (value any, found bool) {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
if len(a.array) == 0 { if len(a.array) == 0 {
@ -646,13 +646,13 @@ func (a *Array) Rand() (value interface{}, found bool) {
} }
// Rands randomly returns `size` items from array(no deleting). // Rands randomly returns `size` items from array(no deleting).
func (a *Array) Rands(size int) []interface{} { func (a *Array) Rands(size int) []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
if size <= 0 || len(a.array) == 0 { if size <= 0 || len(a.array) == 0 {
return nil return nil
} }
array := make([]interface{}, size) array := make([]any, size)
for i := 0; i < size; i++ { for i := 0; i < size; i++ {
array[i] = a.array[grand.Intn(len(a.array))] array[i] = a.array[grand.Intn(len(a.array))]
} }
@ -697,8 +697,8 @@ func (a *Array) Join(glue string) string {
} }
// CountValues counts the number of occurrences of all values in the array. // CountValues counts the number of occurrences of all values in the array.
func (a *Array) CountValues() map[interface{}]int { func (a *Array) CountValues() map[any]int {
m := make(map[interface{}]int) m := make(map[any]int)
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
for _, v := range a.array { for _, v := range a.array {
@ -708,13 +708,13 @@ func (a *Array) CountValues() map[interface{}]int {
} }
// Iterator is alias of IteratorAsc. // Iterator is alias of IteratorAsc.
func (a *Array) Iterator(f func(k int, v interface{}) bool) { func (a *Array) Iterator(f func(k int, v any) bool) {
a.IteratorAsc(f) a.IteratorAsc(f)
} }
// IteratorAsc iterates the array readonly in ascending order with given callback function `f`. // IteratorAsc iterates the array readonly in ascending order with given callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (a *Array) IteratorAsc(f func(k int, v interface{}) bool) { func (a *Array) IteratorAsc(f func(k int, v any) bool) {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
for k, v := range a.array { for k, v := range a.array {
@ -726,7 +726,7 @@ func (a *Array) IteratorAsc(f func(k int, v interface{}) bool) {
// IteratorDesc iterates the array readonly in descending order with given callback function `f`. // IteratorDesc iterates the array readonly in descending order with given callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (a *Array) IteratorDesc(f func(k int, v interface{}) bool) { func (a *Array) IteratorDesc(f func(k int, v any) bool) {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
for i := len(a.array) - 1; i >= 0; i-- { for i := len(a.array) - 1; i >= 0; i-- {
@ -772,7 +772,7 @@ func (a Array) MarshalJSON() ([]byte, error) {
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
func (a *Array) UnmarshalJSON(b []byte) error { func (a *Array) UnmarshalJSON(b []byte) error {
if a.array == nil { if a.array == nil {
a.array = make([]interface{}, 0) a.array = make([]any, 0)
} }
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
@ -783,7 +783,7 @@ func (a *Array) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for array. // UnmarshalValue is an interface implement which sets any type of value for array.
func (a *Array) UnmarshalValue(value interface{}) error { func (a *Array) UnmarshalValue(value any) error {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
switch value.(type) { switch value.(type) {
@ -798,7 +798,7 @@ func (a *Array) UnmarshalValue(value interface{}) error {
// Filter iterates array and filters elements using custom callback function. // Filter iterates array and filters elements using custom callback function.
// It removes the element from array if callback function `filter` returns true, // It removes the element from array if callback function `filter` returns true,
// it or else does nothing and continues iterating. // it or else does nothing and continues iterating.
func (a *Array) Filter(filter func(index int, value interface{}) bool) *Array { func (a *Array) Filter(filter func(index int, value any) bool) *Array {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
for i := 0; i < len(a.array); { for i := 0; i < len(a.array); {
@ -841,7 +841,7 @@ func (a *Array) FilterEmpty() *Array {
} }
// Walk applies a user supplied function `f` to every item of array. // Walk applies a user supplied function `f` to every item of array.
func (a *Array) Walk(f func(value interface{}) interface{}) *Array { func (a *Array) Walk(f func(value any) any) *Array {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
for i, v := range a.array { for i, v := range a.array {
@ -856,13 +856,13 @@ func (a *Array) IsEmpty() bool {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (a *Array) DeepCopy() interface{} { func (a *Array) DeepCopy() any {
if a == nil { if a == nil {
return nil return nil
} }
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
newSlice := make([]interface{}, len(a.array)) newSlice := make([]any, len(a.array))
for i, v := range a.array { for i, v := range a.array {
newSlice[i] = deepcopy.Copy(v) newSlice[i] = deepcopy.Copy(v)
} }

View File

@ -478,11 +478,11 @@ func (a *IntArray) Slice() []int {
return array return array
} }
// Interfaces returns current array as []interface{}. // Interfaces returns current array as []any.
func (a *IntArray) Interfaces() []interface{} { func (a *IntArray) Interfaces() []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
array := make([]interface{}, len(a.array)) array := make([]any, len(a.array))
for k, v := range a.array { for k, v := range a.array {
array[k] = v array[k] = v
} }
@ -581,7 +581,7 @@ func (a *IntArray) RLockFunc(f func(array []int)) *IntArray {
// The parameter `array` can be any garray or slice type. // The parameter `array` can be any garray or slice type.
// The difference between Merge and Append is Append supports only specified slice type, // The difference between Merge and Append is Append supports only specified slice type,
// but Merge supports more parameter types. // but Merge supports more parameter types.
func (a *IntArray) Merge(array interface{}) *IntArray { func (a *IntArray) Merge(array any) *IntArray {
return a.Append(gconv.Ints(array)...) return a.Append(gconv.Ints(array)...)
} }
@ -788,7 +788,7 @@ func (a *IntArray) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for array. // UnmarshalValue is an interface implement which sets any type of value for array.
func (a *IntArray) UnmarshalValue(value interface{}) error { func (a *IntArray) UnmarshalValue(value any) error {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
switch value.(type) { switch value.(type) {
@ -846,7 +846,7 @@ func (a *IntArray) IsEmpty() bool {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (a *IntArray) DeepCopy() interface{} { func (a *IntArray) DeepCopy() any {
if a == nil { if a == nil {
return nil return nil
} }

View File

@ -454,11 +454,11 @@ func (a *StrArray) Slice() []string {
return array return array
} }
// Interfaces returns current array as []interface{}. // Interfaces returns current array as []any.
func (a *StrArray) Interfaces() []interface{} { func (a *StrArray) Interfaces() []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
array := make([]interface{}, len(a.array)) array := make([]any, len(a.array))
for k, v := range a.array { for k, v := range a.array {
array[k] = v array[k] = v
} }
@ -573,7 +573,7 @@ func (a *StrArray) RLockFunc(f func(array []string)) *StrArray {
// The parameter `array` can be any garray or slice type. // The parameter `array` can be any garray or slice type.
// The difference between Merge and Append is Append supports only specified slice type, // The difference between Merge and Append is Append supports only specified slice type,
// but Merge supports more parameter types. // but Merge supports more parameter types.
func (a *StrArray) Merge(array interface{}) *StrArray { func (a *StrArray) Merge(array any) *StrArray {
return a.Append(gconv.Strings(array)...) return a.Append(gconv.Strings(array)...)
} }
@ -787,7 +787,7 @@ func (a *StrArray) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for array. // UnmarshalValue is an interface implement which sets any type of value for array.
func (a *StrArray) UnmarshalValue(value interface{}) error { func (a *StrArray) UnmarshalValue(value any) error {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
switch value.(type) { switch value.(type) {
@ -845,7 +845,7 @@ func (a *StrArray) IsEmpty() bool {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (a *StrArray) DeepCopy() interface{} { func (a *StrArray) DeepCopy() any {
if a == nil { if a == nil {
return nil return nil
} }

View File

@ -29,9 +29,9 @@ import (
// when its initialization and cannot be changed then. // when its initialization and cannot be changed then.
type SortedArray struct { type SortedArray struct {
mu rwmutex.RWMutex mu rwmutex.RWMutex
array []interface{} array []any
unique bool // Whether enable unique feature(false) unique bool // Whether enable unique feature(false)
comparator func(a, b interface{}) int // Comparison function(it returns -1: a < b; 0: a == b; 1: a > b) comparator func(a, b any) int // Comparison function(it returns -1: a < b; 0: a == b; 1: a > b)
} }
// NewSortedArray creates and returns an empty sorted array. // NewSortedArray creates and returns an empty sorted array.
@ -40,28 +40,28 @@ type SortedArray struct {
// if it returns value < 0, means `a` < `b`; the `a` will be inserted before `b`; // if it returns value < 0, means `a` < `b`; the `a` will be inserted before `b`;
// if it returns value = 0, means `a` = `b`; the `a` will be replaced by `b`; // if it returns value = 0, means `a` = `b`; the `a` will be replaced by `b`;
// if it returns value > 0, means `a` > `b`; the `a` will be inserted after `b`; // if it returns value > 0, means `a` > `b`; the `a` will be inserted after `b`;
func NewSortedArray(comparator func(a, b interface{}) int, safe ...bool) *SortedArray { func NewSortedArray(comparator func(a, b any) int, safe ...bool) *SortedArray {
return NewSortedArraySize(0, comparator, safe...) return NewSortedArraySize(0, comparator, safe...)
} }
// NewSortedArraySize create and returns an sorted array with given size and cap. // NewSortedArraySize create and returns an sorted array with given size and cap.
// The parameter `safe` is used to specify whether using array in concurrent-safety, // The parameter `safe` is used to specify whether using array in concurrent-safety,
// which is false in default. // which is false in default.
func NewSortedArraySize(cap int, comparator func(a, b interface{}) int, safe ...bool) *SortedArray { func NewSortedArraySize(cap int, comparator func(a, b any) int, safe ...bool) *SortedArray {
return &SortedArray{ return &SortedArray{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
array: make([]interface{}, 0, cap), array: make([]any, 0, cap),
comparator: comparator, comparator: comparator,
} }
} }
// NewSortedArrayRange creates and returns an array by a range from `start` to `end` // NewSortedArrayRange creates and returns an array by a range from `start` to `end`
// with step value `step`. // with step value `step`.
func NewSortedArrayRange(start, end, step int, comparator func(a, b interface{}) int, safe ...bool) *SortedArray { func NewSortedArrayRange(start, end, step int, comparator func(a, b any) int, safe ...bool) *SortedArray {
if step == 0 { if step == 0 {
panic(fmt.Sprintf(`invalid step value: %d`, step)) panic(fmt.Sprintf(`invalid step value: %d`, step))
} }
slice := make([]interface{}, 0) slice := make([]any, 0)
index := 0 index := 0
for i := start; i <= end; i += step { for i := start; i <= end; i += step {
slice = append(slice, i) slice = append(slice, i)
@ -73,7 +73,7 @@ func NewSortedArrayRange(start, end, step int, comparator func(a, b interface{})
// NewSortedArrayFrom creates and returns an sorted array with given slice `array`. // NewSortedArrayFrom creates and returns an sorted array with given slice `array`.
// The parameter `safe` is used to specify whether using array in concurrent-safety, // The parameter `safe` is used to specify whether using array in concurrent-safety,
// which is false in default. // which is false in default.
func NewSortedArrayFrom(array []interface{}, comparator func(a, b interface{}) int, safe ...bool) *SortedArray { func NewSortedArrayFrom(array []any, comparator func(a, b any) int, safe ...bool) *SortedArray {
a := NewSortedArraySize(0, comparator, safe...) a := NewSortedArraySize(0, comparator, safe...)
a.array = array a.array = array
sort.Slice(a.array, func(i, j int) bool { sort.Slice(a.array, func(i, j int) bool {
@ -85,21 +85,21 @@ func NewSortedArrayFrom(array []interface{}, comparator func(a, b interface{}) i
// NewSortedArrayFromCopy creates and returns an sorted array from a copy of given slice `array`. // NewSortedArrayFromCopy creates and returns an sorted array from a copy of given slice `array`.
// The parameter `safe` is used to specify whether using array in concurrent-safety, // The parameter `safe` is used to specify whether using array in concurrent-safety,
// which is false in default. // which is false in default.
func NewSortedArrayFromCopy(array []interface{}, comparator func(a, b interface{}) int, safe ...bool) *SortedArray { func NewSortedArrayFromCopy(array []any, comparator func(a, b any) int, safe ...bool) *SortedArray {
newArray := make([]interface{}, len(array)) newArray := make([]any, len(array))
copy(newArray, array) copy(newArray, array)
return NewSortedArrayFrom(newArray, comparator, safe...) return NewSortedArrayFrom(newArray, comparator, safe...)
} }
// At returns the value by the specified index. // At returns the value by the specified index.
// If the given `index` is out of range of the array, it returns `nil`. // If the given `index` is out of range of the array, it returns `nil`.
func (a *SortedArray) At(index int) (value interface{}) { func (a *SortedArray) At(index int) (value any) {
value, _ = a.Get(index) value, _ = a.Get(index)
return return
} }
// SetArray sets the underlying slice array with the given `array`. // SetArray sets the underlying slice array with the given `array`.
func (a *SortedArray) SetArray(array []interface{}) *SortedArray { func (a *SortedArray) SetArray(array []any) *SortedArray {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
a.array = array a.array = array
@ -111,7 +111,7 @@ func (a *SortedArray) SetArray(array []interface{}) *SortedArray {
// SetComparator sets/changes the comparator for sorting. // SetComparator sets/changes the comparator for sorting.
// It resorts the array as the comparator is changed. // It resorts the array as the comparator is changed.
func (a *SortedArray) SetComparator(comparator func(a, b interface{}) int) { func (a *SortedArray) SetComparator(comparator func(a, b any) int) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
a.comparator = comparator a.comparator = comparator
@ -134,12 +134,12 @@ func (a *SortedArray) Sort() *SortedArray {
// Add adds one or multiple values to sorted array, the array always keeps sorted. // Add adds one or multiple values to sorted array, the array always keeps sorted.
// It's alias of function Append, see Append. // It's alias of function Append, see Append.
func (a *SortedArray) Add(values ...interface{}) *SortedArray { func (a *SortedArray) Add(values ...any) *SortedArray {
return a.Append(values...) return a.Append(values...)
} }
// Append adds one or multiple values to sorted array, the array always keeps sorted. // Append adds one or multiple values to sorted array, the array always keeps sorted.
func (a *SortedArray) Append(values ...interface{}) *SortedArray { func (a *SortedArray) Append(values ...any) *SortedArray {
if len(values) == 0 { if len(values) == 0 {
return a return a
} }
@ -157,14 +157,14 @@ func (a *SortedArray) Append(values ...interface{}) *SortedArray {
if cmp > 0 { if cmp > 0 {
index++ index++
} }
a.array = append(a.array[:index], append([]interface{}{value}, a.array[index:]...)...) a.array = append(a.array[:index], append([]any{value}, a.array[index:]...)...)
} }
return a return a
} }
// Get returns the value by the specified index. // Get returns the value by the specified index.
// If the given `index` is out of range of the array, the `found` is false. // If the given `index` is out of range of the array, the `found` is false.
func (a *SortedArray) Get(index int) (value interface{}, found bool) { func (a *SortedArray) Get(index int) (value any, found bool) {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
if index < 0 || index >= len(a.array) { if index < 0 || index >= len(a.array) {
@ -175,14 +175,14 @@ func (a *SortedArray) Get(index int) (value interface{}, found bool) {
// Remove removes an item by index. // Remove removes an item by index.
// If the given `index` is out of range of the array, the `found` is false. // If the given `index` is out of range of the array, the `found` is false.
func (a *SortedArray) Remove(index int) (value interface{}, found bool) { func (a *SortedArray) Remove(index int) (value any, found bool) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
return a.doRemoveWithoutLock(index) return a.doRemoveWithoutLock(index)
} }
// doRemoveWithoutLock removes an item by index without lock. // doRemoveWithoutLock removes an item by index without lock.
func (a *SortedArray) doRemoveWithoutLock(index int) (value interface{}, found bool) { func (a *SortedArray) doRemoveWithoutLock(index int) (value any, found bool) {
if index < 0 || index >= len(a.array) { if index < 0 || index >= len(a.array) {
return nil, false return nil, false
} }
@ -206,7 +206,7 @@ func (a *SortedArray) doRemoveWithoutLock(index int) (value interface{}, found b
// RemoveValue removes an item by value. // RemoveValue removes an item by value.
// It returns true if value is found in the array, or else false if not found. // It returns true if value is found in the array, or else false if not found.
func (a *SortedArray) RemoveValue(value interface{}) bool { func (a *SortedArray) RemoveValue(value any) bool {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if i, r := a.binSearch(value, false); r == 0 { if i, r := a.binSearch(value, false); r == 0 {
@ -217,7 +217,7 @@ func (a *SortedArray) RemoveValue(value interface{}) bool {
} }
// RemoveValues removes an item by `values`. // RemoveValues removes an item by `values`.
func (a *SortedArray) RemoveValues(values ...interface{}) { func (a *SortedArray) RemoveValues(values ...any) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
for _, value := range values { for _, value := range values {
@ -229,7 +229,7 @@ func (a *SortedArray) RemoveValues(values ...interface{}) {
// PopLeft pops and returns an item from the beginning of array. // PopLeft pops and returns an item from the beginning of array.
// Note that if the array is empty, the `found` is false. // Note that if the array is empty, the `found` is false.
func (a *SortedArray) PopLeft() (value interface{}, found bool) { func (a *SortedArray) PopLeft() (value any, found bool) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if len(a.array) == 0 { if len(a.array) == 0 {
@ -242,7 +242,7 @@ func (a *SortedArray) PopLeft() (value interface{}, found bool) {
// PopRight pops and returns an item from the end of array. // PopRight pops and returns an item from the end of array.
// Note that if the array is empty, the `found` is false. // Note that if the array is empty, the `found` is false.
func (a *SortedArray) PopRight() (value interface{}, found bool) { func (a *SortedArray) PopRight() (value any, found bool) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
index := len(a.array) - 1 index := len(a.array) - 1
@ -256,14 +256,14 @@ func (a *SortedArray) PopRight() (value interface{}, found bool) {
// PopRand randomly pops and return an item out of array. // PopRand randomly pops and return an item out of array.
// Note that if the array is empty, the `found` is false. // Note that if the array is empty, the `found` is false.
func (a *SortedArray) PopRand() (value interface{}, found bool) { func (a *SortedArray) PopRand() (value any, found bool) {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
return a.doRemoveWithoutLock(grand.Intn(len(a.array))) return a.doRemoveWithoutLock(grand.Intn(len(a.array)))
} }
// PopRands randomly pops and returns `size` items out of array. // PopRands randomly pops and returns `size` items out of array.
func (a *SortedArray) PopRands(size int) []interface{} { func (a *SortedArray) PopRands(size int) []any {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if size <= 0 || len(a.array) == 0 { if size <= 0 || len(a.array) == 0 {
@ -272,7 +272,7 @@ func (a *SortedArray) PopRands(size int) []interface{} {
if size >= len(a.array) { if size >= len(a.array) {
size = len(a.array) size = len(a.array)
} }
array := make([]interface{}, size) array := make([]any, size)
for i := 0; i < size; i++ { for i := 0; i < size; i++ {
array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array))) array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array)))
} }
@ -280,7 +280,7 @@ func (a *SortedArray) PopRands(size int) []interface{} {
} }
// PopLefts pops and returns `size` items from the beginning of array. // PopLefts pops and returns `size` items from the beginning of array.
func (a *SortedArray) PopLefts(size int) []interface{} { func (a *SortedArray) PopLefts(size int) []any {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if size <= 0 || len(a.array) == 0 { if size <= 0 || len(a.array) == 0 {
@ -297,7 +297,7 @@ func (a *SortedArray) PopLefts(size int) []interface{} {
} }
// PopRights pops and returns `size` items from the end of array. // PopRights pops and returns `size` items from the end of array.
func (a *SortedArray) PopRights(size int) []interface{} { func (a *SortedArray) PopRights(size int) []any {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if size <= 0 || len(a.array) == 0 { if size <= 0 || len(a.array) == 0 {
@ -321,7 +321,7 @@ func (a *SortedArray) PopRights(size int) []interface{} {
// If `end` is negative, then the offset will start from the end of array. // If `end` is negative, then the offset will start from the end of array.
// If `end` is omitted, then the sequence will have everything from start up // If `end` is omitted, then the sequence will have everything from start up
// until the end of the array. // until the end of the array.
func (a *SortedArray) Range(start int, end ...int) []interface{} { func (a *SortedArray) Range(start int, end ...int) []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
offsetEnd := len(a.array) offsetEnd := len(a.array)
@ -334,9 +334,9 @@ func (a *SortedArray) Range(start int, end ...int) []interface{} {
if start < 0 { if start < 0 {
start = 0 start = 0
} }
array := ([]interface{})(nil) array := ([]any)(nil)
if a.mu.IsSafe() { if a.mu.IsSafe() {
array = make([]interface{}, offsetEnd-start) array = make([]any, offsetEnd-start)
copy(array, a.array[start:offsetEnd]) copy(array, a.array[start:offsetEnd])
} else { } else {
array = a.array[start:offsetEnd] array = a.array[start:offsetEnd]
@ -357,7 +357,7 @@ func (a *SortedArray) Range(start int, end ...int) []interface{} {
// If it is omitted, then the sequence will have everything from offset up until the end of the array. // If it is omitted, then the sequence will have everything from offset up until the end of the array.
// //
// Any possibility crossing the left border of array, it will fail. // Any possibility crossing the left border of array, it will fail.
func (a *SortedArray) SubSlice(offset int, length ...int) []interface{} { func (a *SortedArray) SubSlice(offset int, length ...int) []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
size := len(a.array) size := len(a.array)
@ -386,7 +386,7 @@ func (a *SortedArray) SubSlice(offset int, length ...int) []interface{} {
size = len(a.array) - offset size = len(a.array) - offset
} }
if a.mu.IsSafe() { if a.mu.IsSafe() {
s := make([]interface{}, size) s := make([]any, size)
copy(s, a.array[offset:]) copy(s, a.array[offset:])
return s return s
} else { } else {
@ -415,12 +415,12 @@ func (a *SortedArray) Len() int {
// Slice returns the underlying data of array. // Slice returns the underlying data of array.
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
// or else a pointer to the underlying data. // or else a pointer to the underlying data.
func (a *SortedArray) Slice() []interface{} { func (a *SortedArray) Slice() []any {
var array []interface{} var array []any
if a.mu.IsSafe() { if a.mu.IsSafe() {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
array = make([]interface{}, len(a.array)) array = make([]any, len(a.array))
copy(array, a.array) copy(array, a.array)
} else { } else {
array = a.array array = a.array
@ -428,19 +428,19 @@ func (a *SortedArray) Slice() []interface{} {
return array return array
} }
// Interfaces returns current array as []interface{}. // Interfaces returns current array as []any.
func (a *SortedArray) Interfaces() []interface{} { func (a *SortedArray) Interfaces() []any {
return a.Slice() return a.Slice()
} }
// Contains checks whether a value exists in the array. // Contains checks whether a value exists in the array.
func (a *SortedArray) Contains(value interface{}) bool { func (a *SortedArray) Contains(value any) bool {
return a.Search(value) != -1 return a.Search(value) != -1
} }
// Search searches array by `value`, returns the index of `value`, // Search searches array by `value`, returns the index of `value`,
// or returns -1 if not exists. // or returns -1 if not exists.
func (a *SortedArray) Search(value interface{}) (index int) { func (a *SortedArray) Search(value any) (index int) {
if i, r := a.binSearch(value, true); r == 0 { if i, r := a.binSearch(value, true); r == 0 {
return i return i
} }
@ -452,7 +452,7 @@ func (a *SortedArray) Search(value interface{}) (index int) {
// If `result` equals to 0, it means the value at `index` is equals to `value`. // If `result` equals to 0, it means the value at `index` is equals to `value`.
// If `result` lesser than 0, it means the value at `index` is lesser than `value`. // If `result` lesser than 0, it means the value at `index` is lesser than `value`.
// If `result` greater than 0, it means the value at `index` is greater than `value`. // If `result` greater than 0, it means the value at `index` is greater than `value`.
func (a *SortedArray) binSearch(value interface{}, lock bool) (index int, result int) { func (a *SortedArray) binSearch(value any, lock bool) (index int, result int) {
if lock { if lock {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
@ -498,13 +498,9 @@ func (a *SortedArray) Unique() *SortedArray {
if len(a.array) == 0 { if len(a.array) == 0 {
return a return a
} }
i := 0 for i := 0; i < len(a.array)-1; {
for {
if i == len(a.array)-1 {
break
}
if a.getComparator()(a.array[i], a.array[i+1]) == 0 { if a.getComparator()(a.array[i], a.array[i+1]) == 0 {
a.array = append(a.array[:i+1], a.array[i+1+1:]...) a.array = append(a.array[:i+1], a.array[i+2:]...)
} else { } else {
i++ i++
} }
@ -515,7 +511,7 @@ func (a *SortedArray) Unique() *SortedArray {
// Clone returns a new array, which is a copy of current array. // Clone returns a new array, which is a copy of current array.
func (a *SortedArray) Clone() (newArray *SortedArray) { func (a *SortedArray) Clone() (newArray *SortedArray) {
a.mu.RLock() a.mu.RLock()
array := make([]interface{}, len(a.array)) array := make([]any, len(a.array))
copy(array, a.array) copy(array, a.array)
a.mu.RUnlock() a.mu.RUnlock()
return NewSortedArrayFrom(array, a.comparator, a.mu.IsSafe()) return NewSortedArrayFrom(array, a.comparator, a.mu.IsSafe())
@ -525,14 +521,14 @@ func (a *SortedArray) Clone() (newArray *SortedArray) {
func (a *SortedArray) Clear() *SortedArray { func (a *SortedArray) Clear() *SortedArray {
a.mu.Lock() a.mu.Lock()
if len(a.array) > 0 { if len(a.array) > 0 {
a.array = make([]interface{}, 0) a.array = make([]any, 0)
} }
a.mu.Unlock() a.mu.Unlock()
return a return a
} }
// LockFunc locks writing by callback function `f`. // LockFunc locks writing by callback function `f`.
func (a *SortedArray) LockFunc(f func(array []interface{})) *SortedArray { func (a *SortedArray) LockFunc(f func(array []any)) *SortedArray {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
@ -546,7 +542,7 @@ func (a *SortedArray) LockFunc(f func(array []interface{})) *SortedArray {
} }
// RLockFunc locks reading by callback function `f`. // RLockFunc locks reading by callback function `f`.
func (a *SortedArray) RLockFunc(f func(array []interface{})) *SortedArray { func (a *SortedArray) RLockFunc(f func(array []any)) *SortedArray {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
f(a.array) f(a.array)
@ -557,14 +553,14 @@ func (a *SortedArray) RLockFunc(f func(array []interface{})) *SortedArray {
// The parameter `array` can be any garray or slice type. // The parameter `array` can be any garray or slice type.
// The difference between Merge and Append is Append supports only specified slice type, // The difference between Merge and Append is Append supports only specified slice type,
// but Merge supports more parameter types. // but Merge supports more parameter types.
func (a *SortedArray) Merge(array interface{}) *SortedArray { func (a *SortedArray) Merge(array any) *SortedArray {
return a.Add(gconv.Interfaces(array)...) return a.Add(gconv.Interfaces(array)...)
} }
// Chunk splits an array into multiple arrays, // Chunk splits an array into multiple arrays,
// the size of each array is determined by `size`. // the size of each array is determined by `size`.
// The last chunk may contain less than size elements. // The last chunk may contain less than size elements.
func (a *SortedArray) Chunk(size int) [][]interface{} { func (a *SortedArray) Chunk(size int) [][]any {
if size < 1 { if size < 1 {
return nil return nil
} }
@ -572,7 +568,7 @@ func (a *SortedArray) Chunk(size int) [][]interface{} {
defer a.mu.RUnlock() defer a.mu.RUnlock()
length := len(a.array) length := len(a.array)
chunks := int(math.Ceil(float64(length) / float64(size))) chunks := int(math.Ceil(float64(length) / float64(size)))
var n [][]interface{} var n [][]any
for i, end := 0, 0; chunks > 0; chunks-- { for i, end := 0, 0; chunks > 0; chunks-- {
end = (i + 1) * size end = (i + 1) * size
if end > length { if end > length {
@ -585,7 +581,7 @@ func (a *SortedArray) Chunk(size int) [][]interface{} {
} }
// Rand randomly returns one item from array(no deleting). // Rand randomly returns one item from array(no deleting).
func (a *SortedArray) Rand() (value interface{}, found bool) { func (a *SortedArray) Rand() (value any, found bool) {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
if len(a.array) == 0 { if len(a.array) == 0 {
@ -595,13 +591,13 @@ func (a *SortedArray) Rand() (value interface{}, found bool) {
} }
// Rands randomly returns `size` items from array(no deleting). // Rands randomly returns `size` items from array(no deleting).
func (a *SortedArray) Rands(size int) []interface{} { func (a *SortedArray) Rands(size int) []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
if size <= 0 || len(a.array) == 0 { if size <= 0 || len(a.array) == 0 {
return nil return nil
} }
array := make([]interface{}, size) array := make([]any, size)
for i := 0; i < size; i++ { for i := 0; i < size; i++ {
array[i] = a.array[grand.Intn(len(a.array))] array[i] = a.array[grand.Intn(len(a.array))]
} }
@ -626,8 +622,8 @@ func (a *SortedArray) Join(glue string) string {
} }
// CountValues counts the number of occurrences of all values in the array. // CountValues counts the number of occurrences of all values in the array.
func (a *SortedArray) CountValues() map[interface{}]int { func (a *SortedArray) CountValues() map[any]int {
m := make(map[interface{}]int) m := make(map[any]int)
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
for _, v := range a.array { for _, v := range a.array {
@ -637,13 +633,13 @@ func (a *SortedArray) CountValues() map[interface{}]int {
} }
// Iterator is alias of IteratorAsc. // Iterator is alias of IteratorAsc.
func (a *SortedArray) Iterator(f func(k int, v interface{}) bool) { func (a *SortedArray) Iterator(f func(k int, v any) bool) {
a.IteratorAsc(f) a.IteratorAsc(f)
} }
// IteratorAsc iterates the array readonly in ascending order with given callback function `f`. // IteratorAsc iterates the array readonly in ascending order with given callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (a *SortedArray) IteratorAsc(f func(k int, v interface{}) bool) { func (a *SortedArray) IteratorAsc(f func(k int, v any) bool) {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
for k, v := range a.array { for k, v := range a.array {
@ -655,7 +651,7 @@ func (a *SortedArray) IteratorAsc(f func(k int, v interface{}) bool) {
// IteratorDesc iterates the array readonly in descending order with given callback function `f`. // IteratorDesc iterates the array readonly in descending order with given callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (a *SortedArray) IteratorDesc(f func(k int, v interface{}) bool) { func (a *SortedArray) IteratorDesc(f func(k int, v any) bool) {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
for i := len(a.array) - 1; i >= 0; i-- { for i := len(a.array) - 1; i >= 0; i-- {
@ -702,7 +698,7 @@ func (a SortedArray) MarshalJSON() ([]byte, error) {
// Note that the comparator is set as string comparator in default. // Note that the comparator is set as string comparator in default.
func (a *SortedArray) UnmarshalJSON(b []byte) error { func (a *SortedArray) UnmarshalJSON(b []byte) error {
if a.comparator == nil { if a.comparator == nil {
a.array = make([]interface{}, 0) a.array = make([]any, 0)
a.comparator = gutil.ComparatorString a.comparator = gutil.ComparatorString
} }
a.mu.Lock() a.mu.Lock()
@ -720,7 +716,7 @@ func (a *SortedArray) UnmarshalJSON(b []byte) error {
// UnmarshalValue is an interface implement which sets any type of value for array. // UnmarshalValue is an interface implement which sets any type of value for array.
// Note that the comparator is set as string comparator in default. // Note that the comparator is set as string comparator in default.
func (a *SortedArray) UnmarshalValue(value interface{}) (err error) { func (a *SortedArray) UnmarshalValue(value any) (err error) {
if a.comparator == nil { if a.comparator == nil {
a.comparator = gutil.ComparatorString a.comparator = gutil.ComparatorString
} }
@ -764,7 +760,7 @@ func (a *SortedArray) FilterNil() *SortedArray {
// Filter iterates array and filters elements using custom callback function. // Filter iterates array and filters elements using custom callback function.
// It removes the element from array if callback function `filter` returns true, // It removes the element from array if callback function `filter` returns true,
// it or else does nothing and continues iterating. // it or else does nothing and continues iterating.
func (a *SortedArray) Filter(filter func(index int, value interface{}) bool) *SortedArray { func (a *SortedArray) Filter(filter func(index int, value any) bool) *SortedArray {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
for i := 0; i < len(a.array); { for i := 0; i < len(a.array); {
@ -800,7 +796,7 @@ func (a *SortedArray) FilterEmpty() *SortedArray {
} }
// Walk applies a user supplied function `f` to every item of array. // Walk applies a user supplied function `f` to every item of array.
func (a *SortedArray) Walk(f func(value interface{}) interface{}) *SortedArray { func (a *SortedArray) Walk(f func(value any) any) *SortedArray {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
// Keep the array always sorted. // Keep the array always sorted.
@ -820,7 +816,7 @@ func (a *SortedArray) IsEmpty() bool {
// getComparator returns the comparator if it's previously set, // getComparator returns the comparator if it's previously set,
// or else it panics. // or else it panics.
func (a *SortedArray) getComparator() func(a, b interface{}) int { func (a *SortedArray) getComparator() func(a, b any) int {
if a.comparator == nil { if a.comparator == nil {
panic("comparator is missing for sorted array") panic("comparator is missing for sorted array")
} }
@ -828,13 +824,13 @@ func (a *SortedArray) getComparator() func(a, b interface{}) int {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (a *SortedArray) DeepCopy() interface{} { func (a *SortedArray) DeepCopy() any {
if a == nil { if a == nil {
return nil return nil
} }
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
newSlice := make([]interface{}, len(a.array)) newSlice := make([]any, len(a.array))
for i, v := range a.array { for i, v := range a.array {
newSlice[i] = deepcopy.Copy(v) newSlice[i] = deepcopy.Copy(v)
} }

View File

@ -420,11 +420,11 @@ func (a *SortedIntArray) Slice() []int {
return array return array
} }
// Interfaces returns current array as []interface{}. // Interfaces returns current array as []any.
func (a *SortedIntArray) Interfaces() []interface{} { func (a *SortedIntArray) Interfaces() []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
array := make([]interface{}, len(a.array)) array := make([]any, len(a.array))
for k, v := range a.array { for k, v := range a.array {
array[k] = v array[k] = v
} }
@ -496,13 +496,9 @@ func (a *SortedIntArray) Unique() *SortedIntArray {
if len(a.array) == 0 { if len(a.array) == 0 {
return a return a
} }
i := 0 for i := 0; i < len(a.array)-1; {
for {
if i == len(a.array)-1 {
break
}
if a.getComparator()(a.array[i], a.array[i+1]) == 0 { if a.getComparator()(a.array[i], a.array[i+1]) == 0 {
a.array = append(a.array[:i+1], a.array[i+1+1:]...) a.array = append(a.array[:i+1], a.array[i+2:]...)
} else { } else {
i++ i++
} }
@ -549,7 +545,7 @@ func (a *SortedIntArray) RLockFunc(f func(array []int)) *SortedIntArray {
// The parameter `array` can be any garray or slice type. // The parameter `array` can be any garray or slice type.
// The difference between Merge and Append is Append supports only specified slice type, // The difference between Merge and Append is Append supports only specified slice type,
// but Merge supports more parameter types. // but Merge supports more parameter types.
func (a *SortedIntArray) Merge(array interface{}) *SortedIntArray { func (a *SortedIntArray) Merge(array any) *SortedIntArray {
return a.Add(gconv.Ints(array)...) return a.Add(gconv.Ints(array)...)
} }
@ -691,7 +687,7 @@ func (a *SortedIntArray) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for array. // UnmarshalValue is an interface implement which sets any type of value for array.
func (a *SortedIntArray) UnmarshalValue(value interface{}) (err error) { func (a *SortedIntArray) UnmarshalValue(value any) (err error) {
if a.comparator == nil { if a.comparator == nil {
a.comparator = defaultComparatorInt a.comparator = defaultComparatorInt
} }
@ -775,7 +771,7 @@ func (a *SortedIntArray) getComparator() func(a, b int) int {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (a *SortedIntArray) DeepCopy() interface{} { func (a *SortedIntArray) DeepCopy() any {
if a == nil { if a == nil {
return nil return nil
} }

View File

@ -406,11 +406,11 @@ func (a *SortedStrArray) Slice() []string {
return array return array
} }
// Interfaces returns current array as []interface{}. // Interfaces returns current array as []any.
func (a *SortedStrArray) Interfaces() []interface{} { func (a *SortedStrArray) Interfaces() []any {
a.mu.RLock() a.mu.RLock()
defer a.mu.RUnlock() defer a.mu.RUnlock()
array := make([]interface{}, len(a.array)) array := make([]any, len(a.array))
for k, v := range a.array { for k, v := range a.array {
array[k] = v array[k] = v
} }
@ -498,13 +498,9 @@ func (a *SortedStrArray) Unique() *SortedStrArray {
if len(a.array) == 0 { if len(a.array) == 0 {
return a return a
} }
i := 0 for i := 0; i < len(a.array)-1; {
for {
if i == len(a.array)-1 {
break
}
if a.getComparator()(a.array[i], a.array[i+1]) == 0 { if a.getComparator()(a.array[i], a.array[i+1]) == 0 {
a.array = append(a.array[:i+1], a.array[i+1+1:]...) a.array = append(a.array[:i+1], a.array[i+2:]...)
} else { } else {
i++ i++
} }
@ -551,7 +547,7 @@ func (a *SortedStrArray) RLockFunc(f func(array []string)) *SortedStrArray {
// The parameter `array` can be any garray or slice type. // The parameter `array` can be any garray or slice type.
// The difference between Merge and Append is Append supports only specified slice type, // The difference between Merge and Append is Append supports only specified slice type,
// but Merge supports more parameter types. // but Merge supports more parameter types.
func (a *SortedStrArray) Merge(array interface{}) *SortedStrArray { func (a *SortedStrArray) Merge(array any) *SortedStrArray {
return a.Add(gconv.Strings(array)...) return a.Add(gconv.Strings(array)...)
} }
@ -704,7 +700,7 @@ func (a *SortedStrArray) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for array. // UnmarshalValue is an interface implement which sets any type of value for array.
func (a *SortedStrArray) UnmarshalValue(value interface{}) (err error) { func (a *SortedStrArray) UnmarshalValue(value any) (err error) {
if a.comparator == nil { if a.comparator == nil {
a.comparator = defaultComparatorStr a.comparator = defaultComparatorStr
} }
@ -788,7 +784,7 @@ func (a *SortedStrArray) getComparator() func(a, b string) int {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (a *SortedStrArray) DeepCopy() interface{} { func (a *SortedStrArray) DeepCopy() any {
if a == nil { if a == nil {
return nil return nil
} }

View File

@ -14,12 +14,12 @@ import (
type anySortedArrayItem struct { type anySortedArrayItem struct {
priority int64 priority int64
value interface{} value any
} }
var ( var (
anyArray = garray.NewArray() anyArray = garray.NewArray()
anySortedArray = garray.NewSortedArray(func(a, b interface{}) int { anySortedArray = garray.NewSortedArray(func(a, b any) int {
return int(a.(anySortedArrayItem).priority - b.(anySortedArrayItem).priority) return int(a.(anySortedArrayItem).priority - b.(anySortedArrayItem).priority)
}) })
) )

View File

@ -81,13 +81,13 @@ func ExampleArray_Iterator() {
// Iterator is alias of IteratorAsc, which iterates the array readonly in ascending order // Iterator is alias of IteratorAsc, which iterates the array readonly in ascending order
// with given callback function `f`. // with given callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
array.Iterator(func(k int, v interface{}) bool { array.Iterator(func(k int, v any) bool {
fmt.Println(k, v) fmt.Println(k, v)
return true return true
}) })
// IteratorDesc iterates the array readonly in descending order with given callback function `f`. // IteratorDesc iterates the array readonly in descending order with given callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
array.IteratorDesc(func(k int, v interface{}) bool { array.IteratorDesc(func(k int, v any) bool {
fmt.Println(k, v) fmt.Println(k, v)
return true return true
}) })
@ -163,7 +163,7 @@ func ExampleArray_Chunk() {
} }
func ExampleArray_PopLeft() { func ExampleArray_PopLeft() {
array := garray.NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) array := garray.NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9})
// Any Pop* functions pick, delete and return the item from array. // Any Pop* functions pick, delete and return the item from array.
@ -180,7 +180,7 @@ func ExampleArray_PopLeft() {
} }
func ExampleArray_PopLefts() { func ExampleArray_PopLefts() {
array := garray.NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) array := garray.NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9})
// Any Pop* functions pick, delete and return the item from array. // Any Pop* functions pick, delete and return the item from array.
@ -197,7 +197,7 @@ func ExampleArray_PopLefts() {
} }
func ExampleArray_PopRight() { func ExampleArray_PopRight() {
array := garray.NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) array := garray.NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9})
// Any Pop* functions pick, delete and return the item from array. // Any Pop* functions pick, delete and return the item from array.
@ -214,7 +214,7 @@ func ExampleArray_PopRight() {
} }
func ExampleArray_PopRights() { func ExampleArray_PopRights() {
array := garray.NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) array := garray.NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9})
// Any Pop* functions pick, delete and return the item from array. // Any Pop* functions pick, delete and return the item from array.
@ -265,10 +265,10 @@ func ExampleArray_Merge() {
func ExampleArray_Filter() { func ExampleArray_Filter() {
array1 := garray.NewFrom(g.Slice{0, 1, 2, nil, "", g.Slice{}, "john"}) array1 := garray.NewFrom(g.Slice{0, 1, 2, nil, "", g.Slice{}, "john"})
array2 := garray.NewFrom(g.Slice{0, 1, 2, nil, "", g.Slice{}, "john"}) array2 := garray.NewFrom(g.Slice{0, 1, 2, nil, "", g.Slice{}, "john"})
fmt.Printf("%#v\n", array1.Filter(func(index int, value interface{}) bool { fmt.Printf("%#v\n", array1.Filter(func(index int, value any) bool {
return empty.IsNil(value) return empty.IsNil(value)
}).Slice()) }).Slice())
fmt.Printf("%#v\n", array2.Filter(func(index int, value interface{}) bool { fmt.Printf("%#v\n", array2.Filter(func(index int, value any) bool {
return empty.IsEmpty(value) return empty.IsEmpty(value)
}).Slice()) }).Slice())

View File

@ -131,7 +131,7 @@ func Test_SortedStrArray2(t *testing.T) {
func Test_SortedArray1(t *testing.T) { func Test_SortedArray1(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := []string{"0", "1", "10", "2", "3", "4", "5", "6", "7", "8", "9"} expect := []string{"0", "1", "10", "2", "3", "4", "5", "6", "7", "8", "9"}
array := garray.NewSortedArray(func(v1, v2 interface{}) int { array := garray.NewSortedArray(func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
}) })
for i := 10; i > -1; i-- { for i := 10; i > -1; i-- {
@ -144,7 +144,7 @@ func Test_SortedArray1(t *testing.T) {
func Test_SortedArray2(t *testing.T) { func Test_SortedArray2(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := []string{"0", "1", "10", "2", "3", "4", "5", "6", "7", "8", "9"} expect := []string{"0", "1", "10", "2", "3", "4", "5", "6", "7", "8", "9"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array := garray.NewSortedArray(func1) array := garray.NewSortedArray(func1)
@ -161,7 +161,7 @@ func Test_SortedArray2(t *testing.T) {
func TestNewFromCopy(t *testing.T) { func TestNewFromCopy(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"100", "200", "300", "400", "500", "600"} a1 := []any{"100", "200", "300", "400", "500", "600"}
array1 := garray.NewFromCopy(a1) array1 := garray.NewFromCopy(a1)
t.AssertIN(array1.PopRands(2), a1) t.AssertIN(array1.PopRands(2), a1)
t.Assert(len(array1.PopRands(1)), 1) t.Assert(len(array1.PopRands(1)), 1)

View File

@ -22,10 +22,10 @@ import (
func Test_Array_Basic(t *testing.T) { func Test_Array_Basic(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := []interface{}{0, 1, 2, 3} expect := []any{0, 1, 2, 3}
array := garray.NewArrayFrom(expect) array := garray.NewArrayFrom(expect)
array2 := garray.NewArrayFrom(expect) array2 := garray.NewArrayFrom(expect)
array3 := garray.NewArrayFrom([]interface{}{}) array3 := garray.NewArrayFrom([]any{})
array4 := garray.NewArrayRange(1, 5, 1) array4 := garray.NewArrayRange(1, 5, 1)
t.Assert(array.Slice(), expect) t.Assert(array.Slice(), expect)
@ -86,10 +86,10 @@ func Test_Array_Basic(t *testing.T) {
t.Assert(array.Len(), 4) t.Assert(array.Len(), 4)
array.InsertBefore(0, 100) array.InsertBefore(0, 100)
array.InsertAfter(0, 200) array.InsertAfter(0, 200)
t.Assert(array.Slice(), []interface{}{100, 200, 2, 2, 3, 4}) t.Assert(array.Slice(), []any{100, 200, 2, 2, 3, 4})
array.InsertBefore(5, 300) array.InsertBefore(5, 300)
array.InsertAfter(6, 400) array.InsertAfter(6, 400)
t.Assert(array.Slice(), []interface{}{100, 200, 2, 2, 3, 300, 4, 400}) t.Assert(array.Slice(), []any{100, 200, 2, 2, 3, 300, 4, 400})
t.Assert(array.Clear().Len(), 0) t.Assert(array.Clear().Len(), 0)
err = array.InsertBefore(99, 9900) err = array.InsertBefore(99, 9900)
t.AssertNE(err, nil) t.AssertNE(err, nil)
@ -102,17 +102,17 @@ func Test_Array_Basic(t *testing.T) {
func TestArray_Sort(t *testing.T) { func TestArray_Sort(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect1 := []interface{}{0, 1, 2, 3} expect1 := []any{0, 1, 2, 3}
expect2 := []interface{}{3, 2, 1, 0} expect2 := []any{3, 2, 1, 0}
array := garray.NewArray() array := garray.NewArray()
for i := 3; i >= 0; i-- { for i := 3; i >= 0; i-- {
array.Append(i) array.Append(i)
} }
array.SortFunc(func(v1, v2 interface{}) bool { array.SortFunc(func(v1, v2 any) bool {
return v1.(int) < v2.(int) return v1.(int) < v2.(int)
}) })
t.Assert(array.Slice(), expect1) t.Assert(array.Slice(), expect1)
array.SortFunc(func(v1, v2 interface{}) bool { array.SortFunc(func(v1, v2 any) bool {
return v1.(int) > v2.(int) return v1.(int) > v2.(int)
}) })
t.Assert(array.Slice(), expect2) t.Assert(array.Slice(), expect2)
@ -121,20 +121,20 @@ func TestArray_Sort(t *testing.T) {
func TestArray_Unique(t *testing.T) { func TestArray_Unique(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := []interface{}{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} expect := []any{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5}
array := garray.NewArrayFrom(expect) array := garray.NewArrayFrom(expect)
t.Assert(array.Unique().Slice(), []interface{}{1, 2, 3, 4, 5}) t.Assert(array.Unique().Slice(), []any{1, 2, 3, 4, 5})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := []interface{}{} expect := []any{}
array := garray.NewArrayFrom(expect) array := garray.NewArrayFrom(expect)
t.Assert(array.Unique().Slice(), []interface{}{}) t.Assert(array.Unique().Slice(), []any{})
}) })
} }
func TestArray_PushAndPop(t *testing.T) { func TestArray_PushAndPop(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := []interface{}{0, 1, 2, 3} expect := []any{0, 1, 2, 3}
array := garray.NewArrayFrom(expect) array := garray.NewArrayFrom(expect)
t.Assert(array.Slice(), expect) t.Assert(array.Slice(), expect)
@ -147,24 +147,24 @@ func TestArray_PushAndPop(t *testing.T) {
t.Assert(ok, true) t.Assert(ok, true)
v, ok = array.PopRand() v, ok = array.PopRand()
t.AssertIN(v, []interface{}{1, 2}) t.AssertIN(v, []any{1, 2})
t.Assert(ok, true) t.Assert(ok, true)
v, ok = array.PopRand() v, ok = array.PopRand()
t.AssertIN(v, []interface{}{1, 2}) t.AssertIN(v, []any{1, 2})
t.Assert(ok, true) t.Assert(ok, true)
t.Assert(array.Len(), 0) t.Assert(array.Len(), 0)
array.PushLeft(1).PushRight(2) array.PushLeft(1).PushRight(2)
t.Assert(array.Slice(), []interface{}{1, 2}) t.Assert(array.Slice(), []any{1, 2})
}) })
} }
func TestArray_PopRands(t *testing.T) { func TestArray_PopRands(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{100, 200, 300, 400, 500, 600} a1 := []any{100, 200, 300, 400, 500, 600}
array := garray.NewFromCopy(a1) array := garray.NewFromCopy(a1)
t.AssertIN(array.PopRands(2), []interface{}{100, 200, 300, 400, 500, 600}) t.AssertIN(array.PopRands(2), []any{100, 200, 300, 400, 500, 600})
}) })
} }
@ -247,56 +247,56 @@ func TestArray_PopLeftsAndPopRights(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
value1 := []interface{}{0, 1, 2, 3, 4, 5, 6} value1 := []any{0, 1, 2, 3, 4, 5, 6}
value2 := []interface{}{0, 1, 2, 3, 4, 5, 6} value2 := []any{0, 1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(value1) array1 := garray.NewArrayFrom(value1)
array2 := garray.NewArrayFrom(value2) array2 := garray.NewArrayFrom(value2)
t.Assert(array1.PopLefts(2), []interface{}{0, 1}) t.Assert(array1.PopLefts(2), []any{0, 1})
t.Assert(array1.Slice(), []interface{}{2, 3, 4, 5, 6}) t.Assert(array1.Slice(), []any{2, 3, 4, 5, 6})
t.Assert(array1.PopRights(2), []interface{}{5, 6}) t.Assert(array1.PopRights(2), []any{5, 6})
t.Assert(array1.Slice(), []interface{}{2, 3, 4}) t.Assert(array1.Slice(), []any{2, 3, 4})
t.Assert(array1.PopRights(20), []interface{}{2, 3, 4}) t.Assert(array1.PopRights(20), []any{2, 3, 4})
t.Assert(array1.Slice(), []interface{}{}) t.Assert(array1.Slice(), []any{})
t.Assert(array2.PopLefts(20), []interface{}{0, 1, 2, 3, 4, 5, 6}) t.Assert(array2.PopLefts(20), []any{0, 1, 2, 3, 4, 5, 6})
t.Assert(array2.Slice(), []interface{}{}) t.Assert(array2.Slice(), []any{})
}) })
} }
func TestArray_Range(t *testing.T) { func TestArray_Range(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
value1 := []interface{}{0, 1, 2, 3, 4, 5, 6} value1 := []any{0, 1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(value1) array1 := garray.NewArrayFrom(value1)
array2 := garray.NewArrayFrom(value1, true) array2 := garray.NewArrayFrom(value1, true)
t.Assert(array1.Range(0, 1), []interface{}{0}) t.Assert(array1.Range(0, 1), []any{0})
t.Assert(array1.Range(1, 2), []interface{}{1}) t.Assert(array1.Range(1, 2), []any{1})
t.Assert(array1.Range(0, 2), []interface{}{0, 1}) t.Assert(array1.Range(0, 2), []any{0, 1})
t.Assert(array1.Range(-1, 10), value1) t.Assert(array1.Range(-1, 10), value1)
t.Assert(array1.Range(10, 2), nil) t.Assert(array1.Range(10, 2), nil)
t.Assert(array2.Range(1, 3), []interface{}{1, 2}) t.Assert(array2.Range(1, 3), []any{1, 2})
}) })
} }
func TestArray_Merge(t *testing.T) { func TestArray_Merge(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
if gconv.Int(v1) < gconv.Int(v2) { if gconv.Int(v1) < gconv.Int(v2) {
return 0 return 0
} }
return 1 return 1
} }
i1 := []interface{}{0, 1, 2, 3} i1 := []any{0, 1, 2, 3}
i2 := []interface{}{4, 5, 6, 7} i2 := []any{4, 5, 6, 7}
array1 := garray.NewArrayFrom(i1) array1 := garray.NewArrayFrom(i1)
array2 := garray.NewArrayFrom(i2) array2 := garray.NewArrayFrom(i2)
t.Assert(array1.Merge(array2).Slice(), []interface{}{0, 1, 2, 3, 4, 5, 6, 7}) t.Assert(array1.Merge(array2).Slice(), []any{0, 1, 2, 3, 4, 5, 6, 7})
// s1 := []string{"a", "b", "c", "d"} // s1 := []string{"a", "b", "c", "d"}
s2 := []string{"e", "f"} s2 := []string{"e", "f"}
i3 := garray.NewIntArrayFrom([]int{1, 2, 3}) i3 := garray.NewIntArrayFrom([]int{1, 2, 3})
i4 := garray.NewArrayFrom([]interface{}{3}) i4 := garray.NewArrayFrom([]any{3})
s3 := garray.NewStrArrayFrom([]string{"g", "h"}) s3 := garray.NewStrArrayFrom([]string{"g", "h"})
s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1)
s5 := garray.NewSortedStrArrayFrom(s2) s5 := garray.NewSortedStrArrayFrom(s2)
s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3})
a1 := garray.NewArrayFrom(i1) a1 := garray.NewArrayFrom(i1)
@ -313,92 +313,92 @@ func TestArray_Merge(t *testing.T) {
func TestArray_Fill(t *testing.T) { func TestArray_Fill(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0} a1 := []any{0}
a2 := []interface{}{0} a2 := []any{0}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
array2 := garray.NewArrayFrom(a2, true) array2 := garray.NewArrayFrom(a2, true)
t.Assert(array1.Fill(1, 2, 100), nil) t.Assert(array1.Fill(1, 2, 100), nil)
t.Assert(array1.Slice(), []interface{}{0, 100, 100}) t.Assert(array1.Slice(), []any{0, 100, 100})
t.Assert(array2.Fill(0, 2, 100), nil) t.Assert(array2.Fill(0, 2, 100), nil)
t.Assert(array2.Slice(), []interface{}{100, 100}) t.Assert(array2.Slice(), []any{100, 100})
t.AssertNE(array2.Fill(-1, 2, 100), nil) t.AssertNE(array2.Fill(-1, 2, 100), nil)
t.Assert(array2.Slice(), []interface{}{100, 100}) t.Assert(array2.Slice(), []any{100, 100})
}) })
} }
func TestArray_Chunk(t *testing.T) { func TestArray_Chunk(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5} a1 := []any{1, 2, 3, 4, 5}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
chunks := array1.Chunk(2) chunks := array1.Chunk(2)
t.Assert(len(chunks), 3) t.Assert(len(chunks), 3)
t.Assert(chunks[0], []interface{}{1, 2}) t.Assert(chunks[0], []any{1, 2})
t.Assert(chunks[1], []interface{}{3, 4}) t.Assert(chunks[1], []any{3, 4})
t.Assert(chunks[2], []interface{}{5}) t.Assert(chunks[2], []any{5})
t.Assert(array1.Chunk(0), nil) t.Assert(array1.Chunk(0), nil)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5} a1 := []any{1, 2, 3, 4, 5}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
chunks := array1.Chunk(3) chunks := array1.Chunk(3)
t.Assert(len(chunks), 2) t.Assert(len(chunks), 2)
t.Assert(chunks[0], []interface{}{1, 2, 3}) t.Assert(chunks[0], []any{1, 2, 3})
t.Assert(chunks[1], []interface{}{4, 5}) t.Assert(chunks[1], []any{4, 5})
t.Assert(array1.Chunk(0), nil) t.Assert(array1.Chunk(0), nil)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5, 6} a1 := []any{1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
chunks := array1.Chunk(2) chunks := array1.Chunk(2)
t.Assert(len(chunks), 3) t.Assert(len(chunks), 3)
t.Assert(chunks[0], []interface{}{1, 2}) t.Assert(chunks[0], []any{1, 2})
t.Assert(chunks[1], []interface{}{3, 4}) t.Assert(chunks[1], []any{3, 4})
t.Assert(chunks[2], []interface{}{5, 6}) t.Assert(chunks[2], []any{5, 6})
t.Assert(array1.Chunk(0), nil) t.Assert(array1.Chunk(0), nil)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5, 6} a1 := []any{1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
chunks := array1.Chunk(3) chunks := array1.Chunk(3)
t.Assert(len(chunks), 2) t.Assert(len(chunks), 2)
t.Assert(chunks[0], []interface{}{1, 2, 3}) t.Assert(chunks[0], []any{1, 2, 3})
t.Assert(chunks[1], []interface{}{4, 5, 6}) t.Assert(chunks[1], []any{4, 5, 6})
t.Assert(array1.Chunk(0), nil) t.Assert(array1.Chunk(0), nil)
}) })
} }
func TestArray_Pad(t *testing.T) { func TestArray_Pad(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0} a1 := []any{0}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
t.Assert(array1.Pad(3, 1).Slice(), []interface{}{0, 1, 1}) t.Assert(array1.Pad(3, 1).Slice(), []any{0, 1, 1})
t.Assert(array1.Pad(-4, 1).Slice(), []interface{}{1, 0, 1, 1}) t.Assert(array1.Pad(-4, 1).Slice(), []any{1, 0, 1, 1})
t.Assert(array1.Pad(3, 1).Slice(), []interface{}{1, 0, 1, 1}) t.Assert(array1.Pad(3, 1).Slice(), []any{1, 0, 1, 1})
}) })
} }
func TestArray_SubSlice(t *testing.T) { func TestArray_SubSlice(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} a1 := []any{0, 1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
array2 := garray.NewArrayFrom(a1, true) array2 := garray.NewArrayFrom(a1, true)
t.Assert(array1.SubSlice(0, 2), []interface{}{0, 1}) t.Assert(array1.SubSlice(0, 2), []any{0, 1})
t.Assert(array1.SubSlice(2, 2), []interface{}{2, 3}) t.Assert(array1.SubSlice(2, 2), []any{2, 3})
t.Assert(array1.SubSlice(5, 8), []interface{}{5, 6}) t.Assert(array1.SubSlice(5, 8), []any{5, 6})
t.Assert(array1.SubSlice(9, 1), nil) t.Assert(array1.SubSlice(9, 1), nil)
t.Assert(array1.SubSlice(-2, 2), []interface{}{5, 6}) t.Assert(array1.SubSlice(-2, 2), []any{5, 6})
t.Assert(array1.SubSlice(-9, 2), nil) t.Assert(array1.SubSlice(-9, 2), nil)
t.Assert(array1.SubSlice(1, -2), nil) t.Assert(array1.SubSlice(1, -2), nil)
t.Assert(array2.SubSlice(0, 2), []interface{}{0, 1}) t.Assert(array2.SubSlice(0, 2), []any{0, 1})
}) })
} }
func TestArray_Rand(t *testing.T) { func TestArray_Rand(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} a1 := []any{0, 1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
t.Assert(len(array1.Rands(2)), 2) t.Assert(len(array1.Rands(2)), 2)
t.Assert(len(array1.Rands(10)), 10) t.Assert(len(array1.Rands(10)), 10)
@ -406,7 +406,7 @@ func TestArray_Rand(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
s1 := []interface{}{"a", "b", "c", "d"} s1 := []any{"a", "b", "c", "d"}
a1 := garray.NewArrayFrom(s1) a1 := garray.NewArrayFrom(s1)
i1, ok := a1.Rand() i1, ok := a1.Rand()
t.Assert(ok, true) t.Assert(ok, true)
@ -415,7 +415,7 @@ func TestArray_Rand(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{} a1 := []any{}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
rand, found := array1.Rand() rand, found := array1.Rand()
t.AssertNil(rand) t.AssertNil(rand)
@ -423,7 +423,7 @@ func TestArray_Rand(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{} a1 := []any{}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
rand := array1.Rands(1) rand := array1.Rands(1)
t.AssertNil(rand) t.AssertNil(rand)
@ -432,7 +432,7 @@ func TestArray_Rand(t *testing.T) {
func TestArray_Shuffle(t *testing.T) { func TestArray_Shuffle(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} a1 := []any{0, 1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
t.Assert(array1.Shuffle().Len(), 7) t.Assert(array1.Shuffle().Len(), 7)
}) })
@ -440,27 +440,27 @@ func TestArray_Shuffle(t *testing.T) {
func TestArray_Reverse(t *testing.T) { func TestArray_Reverse(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} a1 := []any{0, 1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
t.Assert(array1.Reverse().Slice(), []interface{}{6, 5, 4, 3, 2, 1, 0}) t.Assert(array1.Reverse().Slice(), []any{6, 5, 4, 3, 2, 1, 0})
}) })
} }
func TestArray_Join(t *testing.T) { func TestArray_Join(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} a1 := []any{0, 1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
t.Assert(array1.Join("."), `0.1.2.3.4.5.6`) t.Assert(array1.Join("."), `0.1.2.3.4.5.6`)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, `"a"`, `\a`} a1 := []any{0, 1, `"a"`, `\a`}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
t.Assert(array1.Join("."), `0.1."a".\a`) t.Assert(array1.Join("."), `0.1."a".\a`)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{} a1 := []any{}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
t.Assert(len(array1.Join(".")), 0) t.Assert(len(array1.Join(".")), 0)
}) })
@ -468,7 +468,7 @@ func TestArray_Join(t *testing.T) {
func TestArray_String(t *testing.T) { func TestArray_String(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} a1 := []any{0, 1, 2, 3, 4, 5, 6}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
t.Assert(array1.String(), `[0,1,2,3,4,5,6]`) t.Assert(array1.String(), `[0,1,2,3,4,5,6]`)
array1 = nil array1 = nil
@ -478,9 +478,9 @@ func TestArray_String(t *testing.T) {
func TestArray_Replace(t *testing.T) { func TestArray_Replace(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} a1 := []any{0, 1, 2, 3, 4, 5, 6}
a2 := []interface{}{"a", "b", "c"} a2 := []any{"a", "b", "c"}
a3 := []interface{}{"m", "n", "p", "z", "x", "y", "d", "u"} a3 := []any{"m", "n", "p", "z", "x", "y", "d", "u"}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
array2 := array1.Replace(a2) array2 := array1.Replace(a2)
t.Assert(array2.Len(), 7) t.Assert(array2.Len(), 7)
@ -497,8 +497,8 @@ func TestArray_Replace(t *testing.T) {
func TestArray_SetArray(t *testing.T) { func TestArray_SetArray(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} a1 := []any{0, 1, 2, 3, 4, 5, 6}
a2 := []interface{}{"a", "b", "c"} a2 := []any{"a", "b", "c"}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
array1 = array1.SetArray(a2) array1 = array1.SetArray(a2)
@ -510,9 +510,9 @@ func TestArray_SetArray(t *testing.T) {
func TestArray_Sum(t *testing.T) { func TestArray_Sum(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3} a1 := []any{0, 1, 2, 3}
a2 := []interface{}{"a", "b", "c"} a2 := []any{"a", "b", "c"}
a3 := []interface{}{"a", "1", "2"} a3 := []any{"a", "1", "2"}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
array2 := garray.NewArrayFrom(a2) array2 := garray.NewArrayFrom(a2)
@ -527,7 +527,7 @@ func TestArray_Sum(t *testing.T) {
func TestArray_Clone(t *testing.T) { func TestArray_Clone(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, 2, 3} a1 := []any{0, 1, 2, 3}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
array2 := array1.Clone() array2 := array1.Clone()
@ -540,7 +540,7 @@ func TestArray_Clone(t *testing.T) {
func TestArray_CountValues(t *testing.T) { func TestArray_CountValues(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "b", "c", "d", "e", "d"} a1 := []any{"a", "b", "c", "d", "e", "d"}
array1 := garray.NewArrayFrom(a1) array1 := garray.NewArrayFrom(a1)
array2 := array1.CountValues() array2 := array1.CountValues()
t.Assert(len(array2), 5) t.Assert(len(array2), 5)
@ -551,13 +551,13 @@ func TestArray_CountValues(t *testing.T) {
func TestArray_LockFunc(t *testing.T) { func TestArray_LockFunc(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
s1 := []interface{}{"a", "b", "c", "d"} s1 := []any{"a", "b", "c", "d"}
a1 := garray.NewArrayFrom(s1, true) a1 := garray.NewArrayFrom(s1, true)
ch1 := make(chan int64, 3) ch1 := make(chan int64, 3)
ch2 := make(chan int64, 3) ch2 := make(chan int64, 3)
// go1 // go1
go a1.LockFunc(func(n1 []interface{}) { // 读写锁 go a1.LockFunc(func(n1 []any) { // 读写锁
time.Sleep(2 * time.Second) // 暂停2秒 time.Sleep(2 * time.Second) // 暂停2秒
n1[2] = "g" n1[2] = "g"
ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000)
@ -583,13 +583,13 @@ func TestArray_LockFunc(t *testing.T) {
func TestArray_RLockFunc(t *testing.T) { func TestArray_RLockFunc(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
s1 := []interface{}{"a", "b", "c", "d"} s1 := []any{"a", "b", "c", "d"}
a1 := garray.NewArrayFrom(s1, true) a1 := garray.NewArrayFrom(s1, true)
ch1 := make(chan int64, 3) ch1 := make(chan int64, 3)
ch2 := make(chan int64, 1) ch2 := make(chan int64, 1)
// go1 // go1
go a1.RLockFunc(func(n1 []interface{}) { // 读锁 go a1.RLockFunc(func(n1 []any) { // 读锁
time.Sleep(2 * time.Second) // 暂停1秒 time.Sleep(2 * time.Second) // 暂停1秒
n1[2] = "g" n1[2] = "g"
ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000)
@ -616,7 +616,7 @@ func TestArray_RLockFunc(t *testing.T) {
func TestArray_Json(t *testing.T) { func TestArray_Json(t *testing.T) {
// pointer // pointer
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
s1 := []interface{}{"a", "b", "d", "c"} s1 := []any{"a", "b", "d", "c"}
a1 := garray.NewArrayFrom(s1) a1 := garray.NewArrayFrom(s1)
b1, err1 := json.Marshal(a1) b1, err1 := json.Marshal(a1)
b2, err2 := json.Marshal(s1) b2, err2 := json.Marshal(s1)
@ -635,7 +635,7 @@ func TestArray_Json(t *testing.T) {
}) })
// value. // value.
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
s1 := []interface{}{"a", "b", "d", "c"} s1 := []any{"a", "b", "d", "c"}
a1 := *garray.NewArrayFrom(s1) a1 := *garray.NewArrayFrom(s1)
b1, err1 := json.Marshal(a1) b1, err1 := json.Marshal(a1)
b2, err2 := json.Marshal(s1) b2, err2 := json.Marshal(s1)
@ -696,26 +696,26 @@ func TestArray_Iterator(t *testing.T) {
slice := g.Slice{"a", "b", "d", "c"} slice := g.Slice{"a", "b", "d", "c"}
array := garray.NewArrayFrom(slice) array := garray.NewArrayFrom(slice)
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array.Iterator(func(k int, v interface{}) bool { array.Iterator(func(k int, v any) bool {
t.Assert(v, slice[k]) t.Assert(v, slice[k])
return true return true
}) })
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array.IteratorAsc(func(k int, v interface{}) bool { array.IteratorAsc(func(k int, v any) bool {
t.Assert(v, slice[k]) t.Assert(v, slice[k])
return true return true
}) })
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array.IteratorDesc(func(k int, v interface{}) bool { array.IteratorDesc(func(k int, v any) bool {
t.Assert(v, slice[k]) t.Assert(v, slice[k])
return true return true
}) })
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
index := 0 index := 0
array.Iterator(func(k int, v interface{}) bool { array.Iterator(func(k int, v any) bool {
index++ index++
return false return false
}) })
@ -723,7 +723,7 @@ func TestArray_Iterator(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
index := 0 index := 0
array.IteratorAsc(func(k int, v interface{}) bool { array.IteratorAsc(func(k int, v any) bool {
index++ index++
return false return false
}) })
@ -731,7 +731,7 @@ func TestArray_Iterator(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
index := 0 index := 0
array.IteratorDesc(func(k int, v interface{}) bool { array.IteratorDesc(func(k int, v any) bool {
index++ index++
return false return false
}) })
@ -805,27 +805,27 @@ func TestArray_Filter(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
values := g.Slice{0, 1, 2, 3, 4, "", g.Slice{}} values := g.Slice{0, 1, 2, 3, 4, "", g.Slice{}}
array := garray.NewArrayFromCopy(values) array := garray.NewArrayFromCopy(values)
t.Assert(array.Filter(func(index int, value interface{}) bool { t.Assert(array.Filter(func(index int, value any) bool {
return empty.IsNil(value) return empty.IsNil(value)
}).Slice(), values) }).Slice(), values)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewArrayFromCopy(g.Slice{nil, 1, 2, 3, 4, nil}) array := garray.NewArrayFromCopy(g.Slice{nil, 1, 2, 3, 4, nil})
t.Assert(array.Filter(func(index int, value interface{}) bool { t.Assert(array.Filter(func(index int, value any) bool {
return empty.IsNil(value) return empty.IsNil(value)
}), g.Slice{1, 2, 3, 4}) }), g.Slice{1, 2, 3, 4})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewArrayFrom(g.Slice{0, 1, 2, 3, 4, "", g.Slice{}}) array := garray.NewArrayFrom(g.Slice{0, 1, 2, 3, 4, "", g.Slice{}})
t.Assert(array.Filter(func(index int, value interface{}) bool { t.Assert(array.Filter(func(index int, value any) bool {
return empty.IsEmpty(value) return empty.IsEmpty(value)
}), g.Slice{1, 2, 3, 4}) }), g.Slice{1, 2, 3, 4})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewArrayFrom(g.Slice{1, 2, 3, 4}) array := garray.NewArrayFrom(g.Slice{1, 2, 3, 4})
t.Assert(array.Filter(func(index int, value interface{}) bool { t.Assert(array.Filter(func(index int, value any) bool {
return empty.IsEmpty(value) return empty.IsEmpty(value)
}), g.Slice{1, 2, 3, 4}) }), g.Slice{1, 2, 3, 4})
}) })
@ -845,7 +845,7 @@ func TestArray_FilterEmpty(t *testing.T) {
func TestArray_Walk(t *testing.T) { func TestArray_Walk(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewArrayFrom(g.Slice{"1", "2"}) array := garray.NewArrayFrom(g.Slice{"1", "2"})
t.Assert(array.Walk(func(value interface{}) interface{} { t.Assert(array.Walk(func(value any) any {
return "key-" + gconv.String(value) return "key-" + gconv.String(value)
}), g.Slice{"key-1", "key-2"}) }), g.Slice{"key-1", "key-2"})
}) })

View File

@ -195,7 +195,7 @@ func TestIntArray_Range(t *testing.T) {
func TestIntArray_Merge(t *testing.T) { func TestIntArray_Merge(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
if gconv.Int(v1) < gconv.Int(v2) { if gconv.Int(v1) < gconv.Int(v2) {
return 0 return 0
} }
@ -204,7 +204,7 @@ func TestIntArray_Merge(t *testing.T) {
n1 := []int{0, 1, 2, 3} n1 := []int{0, 1, 2, 3}
n2 := []int{4, 5, 6, 7} n2 := []int{4, 5, 6, 7}
i1 := []interface{}{"1", "2"} i1 := []any{"1", "2"}
s1 := []string{"a", "b", "c"} s1 := []string{"a", "b", "c"}
s2 := []string{"e", "f"} s2 := []string{"e", "f"}
a1 := garray.NewIntArrayFrom(n1) a1 := garray.NewIntArrayFrom(n1)
@ -216,7 +216,7 @@ func TestIntArray_Merge(t *testing.T) {
a6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) a6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3})
a7 := garray.NewSortedStrArrayFrom(s1) a7 := garray.NewSortedStrArrayFrom(s1)
a8 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) a8 := garray.NewSortedArrayFrom([]any{4, 5}, func1)
t.Assert(a1.Merge(a2).Slice(), []int{0, 1, 2, 3, 4, 5, 6, 7}) t.Assert(a1.Merge(a2).Slice(), []int{0, 1, 2, 3, 4, 5, 6, 7})
t.Assert(a1.Merge(a3).Len(), 10) t.Assert(a1.Merge(a3).Len(), 10)

View File

@ -235,14 +235,14 @@ func TestStrArray_PopLeftsAndPopRights(t *testing.T) {
value2 := []string{"0", "1", "2", "3", "4", "5", "6"} value2 := []string{"0", "1", "2", "3", "4", "5", "6"}
array1 := garray.NewStrArrayFrom(value1) array1 := garray.NewStrArrayFrom(value1)
array2 := garray.NewStrArrayFrom(value2) array2 := garray.NewStrArrayFrom(value2)
t.Assert(array1.PopLefts(2), []interface{}{"0", "1"}) t.Assert(array1.PopLefts(2), []any{"0", "1"})
t.Assert(array1.Slice(), []interface{}{"2", "3", "4", "5", "6"}) t.Assert(array1.Slice(), []any{"2", "3", "4", "5", "6"})
t.Assert(array1.PopRights(2), []interface{}{"5", "6"}) t.Assert(array1.PopRights(2), []any{"5", "6"})
t.Assert(array1.Slice(), []interface{}{"2", "3", "4"}) t.Assert(array1.Slice(), []any{"2", "3", "4"})
t.Assert(array1.PopRights(20), []interface{}{"2", "3", "4"}) t.Assert(array1.PopRights(20), []any{"2", "3", "4"})
t.Assert(array1.Slice(), []interface{}{}) t.Assert(array1.Slice(), []any{})
t.Assert(array2.PopLefts(20), []interface{}{"0", "1", "2", "3", "4", "5", "6"}) t.Assert(array2.PopLefts(20), []any{"0", "1", "2", "3", "4", "5", "6"})
t.Assert(array2.Slice(), []interface{}{}) t.Assert(array2.Slice(), []any{})
}) })
} }
@ -251,12 +251,12 @@ func TestString_Range(t *testing.T) {
value1 := []string{"0", "1", "2", "3", "4", "5", "6"} value1 := []string{"0", "1", "2", "3", "4", "5", "6"}
array1 := garray.NewStrArrayFrom(value1) array1 := garray.NewStrArrayFrom(value1)
array2 := garray.NewStrArrayFrom(value1, true) array2 := garray.NewStrArrayFrom(value1, true)
t.Assert(array1.Range(0, 1), []interface{}{"0"}) t.Assert(array1.Range(0, 1), []any{"0"})
t.Assert(array1.Range(1, 2), []interface{}{"1"}) t.Assert(array1.Range(1, 2), []any{"1"})
t.Assert(array1.Range(0, 2), []interface{}{"0", "1"}) t.Assert(array1.Range(0, 2), []any{"0", "1"})
t.Assert(array1.Range(-1, 10), value1) t.Assert(array1.Range(-1, 10), value1)
t.Assert(array1.Range(10, 1), nil) t.Assert(array1.Range(10, 1), nil)
t.Assert(array2.Range(0, 1), []interface{}{"0"}) t.Assert(array2.Range(0, 1), []any{"0"})
}) })
} }
@ -268,7 +268,7 @@ func TestStrArray_Merge(t *testing.T) {
array2 := garray.NewStrArrayFrom(a21) array2 := garray.NewStrArrayFrom(a21)
t.Assert(array1.Merge(array2).Slice(), []string{"0", "1", "2", "3", "4", "5", "6", "7"}) t.Assert(array1.Merge(array2).Slice(), []string{"0", "1", "2", "3", "4", "5", "6", "7"})
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
if gconv.Int(v1) < gconv.Int(v2) { if gconv.Int(v1) < gconv.Int(v2) {
return 0 return 0
} }
@ -278,9 +278,9 @@ func TestStrArray_Merge(t *testing.T) {
s1 := []string{"a", "b", "c", "d"} s1 := []string{"a", "b", "c", "d"}
s2 := []string{"e", "f"} s2 := []string{"e", "f"}
i1 := garray.NewIntArrayFrom([]int{1, 2, 3}) i1 := garray.NewIntArrayFrom([]int{1, 2, 3})
i2 := garray.NewArrayFrom([]interface{}{3}) i2 := garray.NewArrayFrom([]any{3})
s3 := garray.NewStrArrayFrom([]string{"g", "h"}) s3 := garray.NewStrArrayFrom([]string{"g", "h"})
s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1)
s5 := garray.NewSortedStrArrayFrom(s2) s5 := garray.NewSortedStrArrayFrom(s2)
s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3})
a1 := garray.NewStrArrayFrom(s1) a1 := garray.NewStrArrayFrom(s1)

View File

@ -24,91 +24,91 @@ import (
func TestSortedArray_NewSortedArrayFrom(t *testing.T) { func TestSortedArray_NewSortedArrayFrom(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "f", "c"} a1 := []any{"a", "f", "c"}
a2 := []interface{}{"h", "j", "i", "k"} a2 := []any{"h", "j", "i", "k"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
func2 := func(v1, v2 interface{}) int { func2 := func(v1, v2 any) int {
return -1 return -1
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
array2 := garray.NewSortedArrayFrom(a2, func2) array2 := garray.NewSortedArrayFrom(a2, func2)
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
t.Assert(array1, []interface{}{"a", "c", "f"}) t.Assert(array1, []any{"a", "c", "f"})
t.Assert(array2.Len(), 4) t.Assert(array2.Len(), 4)
t.Assert(array2, []interface{}{"k", "i", "j", "h"}) t.Assert(array2, []any{"k", "i", "j", "h"})
}) })
} }
func TestNewSortedArrayFromCopy(t *testing.T) { func TestNewSortedArrayFromCopy(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "f", "c"} a1 := []any{"a", "f", "c"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
func2 := func(v1, v2 interface{}) int { func2 := func(v1, v2 any) int {
return -1 return -1
} }
array1 := garray.NewSortedArrayFromCopy(a1, func1) array1 := garray.NewSortedArrayFromCopy(a1, func1)
array2 := garray.NewSortedArrayFromCopy(a1, func2) array2 := garray.NewSortedArrayFromCopy(a1, func2)
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
t.Assert(array1, []interface{}{"a", "c", "f"}) t.Assert(array1, []any{"a", "c", "f"})
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
t.Assert(array2, []interface{}{"c", "f", "a"}) t.Assert(array2, []any{"c", "f", "a"})
}) })
} }
func TestNewSortedArrayRange(t *testing.T) { func TestNewSortedArrayRange(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return gconv.Int(v1) - gconv.Int(v2) return gconv.Int(v1) - gconv.Int(v2)
} }
array1 := garray.NewSortedArrayRange(1, 5, 1, func1) array1 := garray.NewSortedArrayRange(1, 5, 1, func1)
t.Assert(array1.Len(), 5) t.Assert(array1.Len(), 5)
t.Assert(array1, []interface{}{1, 2, 3, 4, 5}) t.Assert(array1, []any{1, 2, 3, 4, 5})
}) })
} }
func TestSortedArray_SetArray(t *testing.T) { func TestSortedArray_SetArray(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "f", "c"} a1 := []any{"a", "f", "c"}
a2 := []interface{}{"e", "h", "g", "k"} a2 := []any{"e", "h", "g", "k"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
array1.SetArray(a2) array1.SetArray(a2)
t.Assert(array1.Len(), 4) t.Assert(array1.Len(), 4)
t.Assert(array1, []interface{}{"e", "g", "h", "k"}) t.Assert(array1, []any{"e", "g", "h", "k"})
}) })
} }
func TestSortedArray_Sort(t *testing.T) { func TestSortedArray_Sort(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "f", "c"} a1 := []any{"a", "f", "c"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
array1.Sort() array1.Sort()
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
t.Assert(array1, []interface{}{"a", "c", "f"}) t.Assert(array1, []any{"a", "c", "f"})
}) })
} }
func TestSortedArray_Get(t *testing.T) { func TestSortedArray_Get(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "f", "c"} a1 := []any{"a", "f", "c"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
@ -129,8 +129,8 @@ func TestSortedArray_Get(t *testing.T) {
func TestSortedArray_At(t *testing.T) { func TestSortedArray_At(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "f", "c"} a1 := []any{"a", "f", "c"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
@ -141,8 +141,8 @@ func TestSortedArray_At(t *testing.T) {
func TestSortedArray_Remove(t *testing.T) { func TestSortedArray_Remove(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b"} a1 := []any{"a", "d", "c", "b"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
@ -178,14 +178,14 @@ func TestSortedArray_Remove(t *testing.T) {
func TestSortedArray_PopLeft(t *testing.T) { func TestSortedArray_PopLeft(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array1 := garray.NewSortedArrayFrom( array1 := garray.NewSortedArrayFrom(
[]interface{}{"a", "d", "c", "b"}, []any{"a", "d", "c", "b"},
gutil.ComparatorString, gutil.ComparatorString,
) )
i1, ok := array1.PopLeft() i1, ok := array1.PopLeft()
t.Assert(ok, true) t.Assert(ok, true)
t.Assert(gconv.String(i1), "a") t.Assert(gconv.String(i1), "a")
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
t.Assert(array1, []interface{}{"b", "c", "d"}) t.Assert(array1, []any{"b", "c", "d"})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3}, gutil.ComparatorInt) array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3}, gutil.ComparatorInt)
@ -207,14 +207,14 @@ func TestSortedArray_PopLeft(t *testing.T) {
func TestSortedArray_PopRight(t *testing.T) { func TestSortedArray_PopRight(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array1 := garray.NewSortedArrayFrom( array1 := garray.NewSortedArrayFrom(
[]interface{}{"a", "d", "c", "b"}, []any{"a", "d", "c", "b"},
gutil.ComparatorString, gutil.ComparatorString,
) )
i1, ok := array1.PopRight() i1, ok := array1.PopRight()
t.Assert(ok, true) t.Assert(ok, true)
t.Assert(gconv.String(i1), "d") t.Assert(gconv.String(i1), "d")
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
t.Assert(array1, []interface{}{"a", "b", "c"}) t.Assert(array1, []any{"a", "b", "c"})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3}, gutil.ComparatorInt) array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3}, gutil.ComparatorInt)
@ -237,14 +237,14 @@ func TestSortedArray_PopRight(t *testing.T) {
func TestSortedArray_PopRand(t *testing.T) { func TestSortedArray_PopRand(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b"} a1 := []any{"a", "d", "c", "b"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
i1, ok := array1.PopRand() i1, ok := array1.PopRand()
t.Assert(ok, true) t.Assert(ok, true)
t.AssertIN(i1, []interface{}{"a", "d", "c", "b"}) t.AssertIN(i1, []any{"a", "d", "c", "b"})
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
}) })
@ -252,19 +252,19 @@ func TestSortedArray_PopRand(t *testing.T) {
func TestSortedArray_PopRands(t *testing.T) { func TestSortedArray_PopRands(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b"} a1 := []any{"a", "d", "c", "b"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
i1 := array1.PopRands(2) i1 := array1.PopRands(2)
t.Assert(len(i1), 2) t.Assert(len(i1), 2)
t.AssertIN(i1, []interface{}{"a", "d", "c", "b"}) t.AssertIN(i1, []any{"a", "d", "c", "b"})
t.Assert(array1.Len(), 2) t.Assert(array1.Len(), 2)
i2 := array1.PopRands(3) i2 := array1.PopRands(3)
t.Assert(len(i1), 2) t.Assert(len(i1), 2)
t.AssertIN(i2, []interface{}{"a", "d", "c", "b"}) t.AssertIN(i2, []any{"a", "d", "c", "b"})
t.Assert(array1.Len(), 0) t.Assert(array1.Len(), 0)
}) })
@ -292,33 +292,33 @@ func TestSortedArray_Empty(t *testing.T) {
func TestSortedArray_PopLefts(t *testing.T) { func TestSortedArray_PopLefts(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b", "e", "f"} a1 := []any{"a", "d", "c", "b", "e", "f"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
i1 := array1.PopLefts(2) i1 := array1.PopLefts(2)
t.Assert(len(i1), 2) t.Assert(len(i1), 2)
t.AssertIN(i1, []interface{}{"a", "d", "c", "b", "e", "f"}) t.AssertIN(i1, []any{"a", "d", "c", "b", "e", "f"})
t.Assert(array1.Len(), 4) t.Assert(array1.Len(), 4)
i2 := array1.PopLefts(5) i2 := array1.PopLefts(5)
t.Assert(len(i2), 4) t.Assert(len(i2), 4)
t.AssertIN(i1, []interface{}{"a", "d", "c", "b", "e", "f"}) t.AssertIN(i1, []any{"a", "d", "c", "b", "e", "f"})
t.Assert(array1.Len(), 0) t.Assert(array1.Len(), 0)
}) })
} }
func TestSortedArray_PopRights(t *testing.T) { func TestSortedArray_PopRights(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b", "e", "f"} a1 := []any{"a", "d", "c", "b", "e", "f"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
i1 := array1.PopRights(2) i1 := array1.PopRights(2)
t.Assert(len(i1), 2) t.Assert(len(i1), 2)
t.Assert(i1, []interface{}{"e", "f"}) t.Assert(i1, []any{"e", "f"})
t.Assert(array1.Len(), 4) t.Assert(array1.Len(), 4)
i2 := array1.PopRights(10) i2 := array1.PopRights(10)
@ -329,36 +329,36 @@ func TestSortedArray_PopRights(t *testing.T) {
func TestSortedArray_Range(t *testing.T) { func TestSortedArray_Range(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b", "e", "f"} a1 := []any{"a", "d", "c", "b", "e", "f"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
array2 := garray.NewSortedArrayFrom(a1, func1, true) array2 := garray.NewSortedArrayFrom(a1, func1, true)
i1 := array1.Range(2, 5) i1 := array1.Range(2, 5)
t.Assert(i1, []interface{}{"c", "d", "e"}) t.Assert(i1, []any{"c", "d", "e"})
t.Assert(array1.Len(), 6) t.Assert(array1.Len(), 6)
i2 := array1.Range(7, 5) i2 := array1.Range(7, 5)
t.Assert(len(i2), 0) t.Assert(len(i2), 0)
i2 = array1.Range(-1, 2) i2 = array1.Range(-1, 2)
t.Assert(i2, []interface{}{"a", "b"}) t.Assert(i2, []any{"a", "b"})
i2 = array1.Range(4, 10) i2 = array1.Range(4, 10)
t.Assert(len(i2), 2) t.Assert(len(i2), 2)
t.Assert(i2, []interface{}{"e", "f"}) t.Assert(i2, []any{"e", "f"})
t.Assert(array2.Range(1, 3), []interface{}{"b", "c"}) t.Assert(array2.Range(1, 3), []any{"b", "c"})
}) })
} }
func TestSortedArray_Sum(t *testing.T) { func TestSortedArray_Sum(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b", "e", "f"} a1 := []any{"a", "d", "c", "b", "e", "f"}
a2 := []interface{}{"1", "2", "3", "b", "e", "f"} a2 := []any{"1", "2", "3", "b", "e", "f"}
a3 := []interface{}{"4", "5", "6"} a3 := []any{"4", "5", "6"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
@ -373,9 +373,9 @@ func TestSortedArray_Sum(t *testing.T) {
func TestSortedArray_Clone(t *testing.T) { func TestSortedArray_Clone(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b", "e", "f"} a1 := []any{"a", "d", "c", "b", "e", "f"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
@ -389,9 +389,9 @@ func TestSortedArray_Clone(t *testing.T) {
func TestSortedArray_Clear(t *testing.T) { func TestSortedArray_Clear(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b", "e", "f"} a1 := []any{"a", "d", "c", "b", "e", "f"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
@ -404,66 +404,66 @@ func TestSortedArray_Clear(t *testing.T) {
func TestSortedArray_Chunk(t *testing.T) { func TestSortedArray_Chunk(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b", "e"} a1 := []any{"a", "d", "c", "b", "e"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
i1 := array1.Chunk(2) i1 := array1.Chunk(2)
t.Assert(len(i1), 3) t.Assert(len(i1), 3)
t.Assert(i1[0], []interface{}{"a", "b"}) t.Assert(i1[0], []any{"a", "b"})
t.Assert(i1[2], []interface{}{"e"}) t.Assert(i1[2], []any{"e"})
i1 = array1.Chunk(0) i1 = array1.Chunk(0)
t.Assert(len(i1), 0) t.Assert(len(i1), 0)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5} a1 := []any{1, 2, 3, 4, 5}
array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt)
chunks := array1.Chunk(3) chunks := array1.Chunk(3)
t.Assert(len(chunks), 2) t.Assert(len(chunks), 2)
t.Assert(chunks[0], []interface{}{1, 2, 3}) t.Assert(chunks[0], []any{1, 2, 3})
t.Assert(chunks[1], []interface{}{4, 5}) t.Assert(chunks[1], []any{4, 5})
t.Assert(array1.Chunk(0), nil) t.Assert(array1.Chunk(0), nil)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5, 6} a1 := []any{1, 2, 3, 4, 5, 6}
array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt)
chunks := array1.Chunk(2) chunks := array1.Chunk(2)
t.Assert(len(chunks), 3) t.Assert(len(chunks), 3)
t.Assert(chunks[0], []interface{}{1, 2}) t.Assert(chunks[0], []any{1, 2})
t.Assert(chunks[1], []interface{}{3, 4}) t.Assert(chunks[1], []any{3, 4})
t.Assert(chunks[2], []interface{}{5, 6}) t.Assert(chunks[2], []any{5, 6})
t.Assert(array1.Chunk(0), nil) t.Assert(array1.Chunk(0), nil)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5, 6} a1 := []any{1, 2, 3, 4, 5, 6}
array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt)
chunks := array1.Chunk(3) chunks := array1.Chunk(3)
t.Assert(len(chunks), 2) t.Assert(len(chunks), 2)
t.Assert(chunks[0], []interface{}{1, 2, 3}) t.Assert(chunks[0], []any{1, 2, 3})
t.Assert(chunks[1], []interface{}{4, 5, 6}) t.Assert(chunks[1], []any{4, 5, 6})
t.Assert(array1.Chunk(0), nil) t.Assert(array1.Chunk(0), nil)
}) })
} }
func TestSortedArray_SubSlice(t *testing.T) { func TestSortedArray_SubSlice(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "b", "e"} a1 := []any{"a", "d", "c", "b", "e"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
array2 := garray.NewSortedArrayFrom(a1, func1, true) array2 := garray.NewSortedArrayFrom(a1, func1, true)
i1 := array1.SubSlice(2, 3) i1 := array1.SubSlice(2, 3)
t.Assert(len(i1), 3) t.Assert(len(i1), 3)
t.Assert(i1, []interface{}{"c", "d", "e"}) t.Assert(i1, []any{"c", "d", "e"})
i1 = array1.SubSlice(2, 6) i1 = array1.SubSlice(2, 6)
t.Assert(len(i1), 3) t.Assert(len(i1), 3)
t.Assert(i1, []interface{}{"c", "d", "e"}) t.Assert(i1, []any{"c", "d", "e"})
i1 = array1.SubSlice(7, 2) i1 = array1.SubSlice(7, 2)
t.Assert(len(i1), 0) t.Assert(len(i1), 0)
@ -473,25 +473,25 @@ func TestSortedArray_SubSlice(t *testing.T) {
s1 = array1.SubSlice(-9, 2) s1 = array1.SubSlice(-9, 2)
t.Assert(s1, nil) t.Assert(s1, nil)
t.Assert(array2.SubSlice(1, 3), []interface{}{"b", "c", "d"}) t.Assert(array2.SubSlice(1, 3), []any{"b", "c", "d"})
}) })
} }
func TestSortedArray_Rand(t *testing.T) { func TestSortedArray_Rand(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c"} a1 := []any{"a", "d", "c"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
i1, ok := array1.Rand() i1, ok := array1.Rand()
t.Assert(ok, true) t.Assert(ok, true)
t.AssertIN(i1, []interface{}{"a", "d", "c"}) t.AssertIN(i1, []any{"a", "d", "c"})
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
array2 := garray.NewSortedArrayFrom([]interface{}{}, func1) array2 := garray.NewSortedArrayFrom([]any{}, func1)
v, ok := array2.Rand() v, ok := array2.Rand()
t.Assert(ok, false) t.Assert(ok, false)
t.Assert(v, nil) t.Assert(v, nil)
@ -500,21 +500,21 @@ func TestSortedArray_Rand(t *testing.T) {
func TestSortedArray_Rands(t *testing.T) { func TestSortedArray_Rands(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c"} a1 := []any{"a", "d", "c"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
i1 := array1.Rands(2) i1 := array1.Rands(2)
t.AssertIN(i1, []interface{}{"a", "d", "c"}) t.AssertIN(i1, []any{"a", "d", "c"})
t.Assert(len(i1), 2) t.Assert(len(i1), 2)
t.Assert(array1.Len(), 3) t.Assert(array1.Len(), 3)
i1 = array1.Rands(4) i1 = array1.Rands(4)
t.Assert(len(i1), 4) t.Assert(len(i1), 4)
array2 := garray.NewSortedArrayFrom([]interface{}{}, func1) array2 := garray.NewSortedArrayFrom([]any{}, func1)
v := array2.Rands(1) v := array2.Rands(1)
t.Assert(v, nil) t.Assert(v, nil)
}) })
@ -522,8 +522,8 @@ func TestSortedArray_Rands(t *testing.T) {
func TestSortedArray_Join(t *testing.T) { func TestSortedArray_Join(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c"} a1 := []any{"a", "d", "c"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
@ -532,13 +532,13 @@ func TestSortedArray_Join(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, `"a"`, `\a`} a1 := []any{0, 1, `"a"`, `\a`}
array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString) array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString)
t.Assert(array1.Join("."), `"a".0.1.\a`) t.Assert(array1.Join("."), `"a".0.1.\a`)
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{} a1 := []any{}
array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString) array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString)
t.Assert(array1.Join("."), "") t.Assert(array1.Join("."), "")
}) })
@ -546,7 +546,7 @@ func TestSortedArray_Join(t *testing.T) {
func TestSortedArray_String(t *testing.T) { func TestSortedArray_String(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{0, 1, "a", "b"} a1 := []any{0, 1, "a", "b"}
array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString) array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString)
t.Assert(array1.String(), `[0,1,"a","b"]`) t.Assert(array1.String(), `[0,1,"a","b"]`)
@ -557,9 +557,9 @@ func TestSortedArray_String(t *testing.T) {
func TestSortedArray_CountValues(t *testing.T) { func TestSortedArray_CountValues(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{"a", "d", "c", "c"} a1 := []any{"a", "d", "c", "c"}
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
array1 := garray.NewSortedArrayFrom(a1, func1) array1 := garray.NewSortedArrayFrom(a1, func1)
@ -573,41 +573,41 @@ func TestSortedArray_CountValues(t *testing.T) {
func TestSortedArray_SetUnique(t *testing.T) { func TestSortedArray_SetUnique(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} a1 := []any{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5}
array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt)
array1.SetUnique(true) array1.SetUnique(true)
t.Assert(array1.Len(), 5) t.Assert(array1.Len(), 5)
t.Assert(array1, []interface{}{1, 2, 3, 4, 5}) t.Assert(array1, []any{1, 2, 3, 4, 5})
}) })
} }
func TestSortedArray_Unique(t *testing.T) { func TestSortedArray_Unique(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a1 := []interface{}{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} a1 := []any{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5}
array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt)
array1.Unique() array1.Unique()
t.Assert(array1.Len(), 5) t.Assert(array1.Len(), 5)
t.Assert(array1, []interface{}{1, 2, 3, 4, 5}) t.Assert(array1, []any{1, 2, 3, 4, 5})
array2 := garray.NewSortedArrayFrom([]interface{}{}, gutil.ComparatorInt) array2 := garray.NewSortedArrayFrom([]any{}, gutil.ComparatorInt)
array2.Unique() array2.Unique()
t.Assert(array2.Len(), 0) t.Assert(array2.Len(), 0)
t.Assert(array2, []interface{}{}) t.Assert(array2, []any{})
}) })
} }
func TestSortedArray_LockFunc(t *testing.T) { func TestSortedArray_LockFunc(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
s1 := []interface{}{"a", "b", "c", "d"} s1 := []any{"a", "b", "c", "d"}
a1 := garray.NewSortedArrayFrom(s1, func1, true) a1 := garray.NewSortedArrayFrom(s1, func1, true)
ch1 := make(chan int64, 3) ch1 := make(chan int64, 3)
ch2 := make(chan int64, 3) ch2 := make(chan int64, 3)
// go1 // go1
go a1.LockFunc(func(n1 []interface{}) { // 读写锁 go a1.LockFunc(func(n1 []any) { // 读写锁
time.Sleep(2 * time.Second) // 暂停2秒 time.Sleep(2 * time.Second) // 暂停2秒
n1[2] = "g" n1[2] = "g"
ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000)
@ -633,16 +633,16 @@ func TestSortedArray_LockFunc(t *testing.T) {
func TestSortedArray_RLockFunc(t *testing.T) { func TestSortedArray_RLockFunc(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
return strings.Compare(gconv.String(v1), gconv.String(v2)) return strings.Compare(gconv.String(v1), gconv.String(v2))
} }
s1 := []interface{}{"a", "b", "c", "d"} s1 := []any{"a", "b", "c", "d"}
a1 := garray.NewSortedArrayFrom(s1, func1, true) a1 := garray.NewSortedArrayFrom(s1, func1, true)
ch1 := make(chan int64, 3) ch1 := make(chan int64, 3)
ch2 := make(chan int64, 3) ch2 := make(chan int64, 3)
// go1 // go1
go a1.RLockFunc(func(n1 []interface{}) { // 读写锁 go a1.RLockFunc(func(n1 []any) { // 读写锁
time.Sleep(2 * time.Second) // 暂停2秒 time.Sleep(2 * time.Second) // 暂停2秒
n1[2] = "g" n1[2] = "g"
ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000)
@ -668,19 +668,19 @@ func TestSortedArray_RLockFunc(t *testing.T) {
func TestSortedArray_Merge(t *testing.T) { func TestSortedArray_Merge(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
if gconv.Int(v1) < gconv.Int(v2) { if gconv.Int(v1) < gconv.Int(v2) {
return 0 return 0
} }
return 1 return 1
} }
s1 := []interface{}{"a", "b", "c", "d"} s1 := []any{"a", "b", "c", "d"}
s2 := []string{"e", "f"} s2 := []string{"e", "f"}
i1 := garray.NewIntArrayFrom([]int{1, 2, 3}) i1 := garray.NewIntArrayFrom([]int{1, 2, 3})
i2 := garray.NewArrayFrom([]interface{}{3}) i2 := garray.NewArrayFrom([]any{3})
s3 := garray.NewStrArrayFrom([]string{"g", "h"}) s3 := garray.NewStrArrayFrom([]string{"g", "h"})
s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1)
s5 := garray.NewSortedStrArrayFrom(s2) s5 := garray.NewSortedStrArrayFrom(s2)
s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3})
@ -699,8 +699,8 @@ func TestSortedArray_Merge(t *testing.T) {
func TestSortedArray_Json(t *testing.T) { func TestSortedArray_Json(t *testing.T) {
// array pointer // array pointer
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
s1 := []interface{}{"a", "b", "d", "c"} s1 := []any{"a", "b", "d", "c"}
s2 := []interface{}{"a", "b", "c", "d"} s2 := []any{"a", "b", "c", "d"}
a1 := garray.NewSortedArrayFrom(s1, gutil.ComparatorString) a1 := garray.NewSortedArrayFrom(s1, gutil.ComparatorString)
b1, err1 := json.Marshal(a1) b1, err1 := json.Marshal(a1)
b2, err2 := json.Marshal(s1) b2, err2 := json.Marshal(s1)
@ -720,8 +720,8 @@ func TestSortedArray_Json(t *testing.T) {
}) })
// array value // array value
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
s1 := []interface{}{"a", "b", "d", "c"} s1 := []any{"a", "b", "d", "c"}
s2 := []interface{}{"a", "b", "c", "d"} s2 := []any{"a", "b", "c", "d"}
a1 := *garray.NewSortedArrayFrom(s1, gutil.ComparatorString) a1 := *garray.NewSortedArrayFrom(s1, gutil.ComparatorString)
b1, err1 := json.Marshal(a1) b1, err1 := json.Marshal(a1)
b2, err2 := json.Marshal(s1) b2, err2 := json.Marshal(s1)
@ -817,26 +817,26 @@ func TestSortedArray_Iterator(t *testing.T) {
slice := g.Slice{"a", "b", "d", "c"} slice := g.Slice{"a", "b", "d", "c"}
array := garray.NewSortedArrayFrom(slice, gutil.ComparatorString) array := garray.NewSortedArrayFrom(slice, gutil.ComparatorString)
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array.Iterator(func(k int, v interface{}) bool { array.Iterator(func(k int, v any) bool {
t.Assert(v, slice[k]) t.Assert(v, slice[k])
return true return true
}) })
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array.IteratorAsc(func(k int, v interface{}) bool { array.IteratorAsc(func(k int, v any) bool {
t.Assert(v, slice[k]) t.Assert(v, slice[k])
return true return true
}) })
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array.IteratorDesc(func(k int, v interface{}) bool { array.IteratorDesc(func(k int, v any) bool {
t.Assert(v, slice[k]) t.Assert(v, slice[k])
return true return true
}) })
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
index := 0 index := 0
array.Iterator(func(k int, v interface{}) bool { array.Iterator(func(k int, v any) bool {
index++ index++
return false return false
}) })
@ -844,7 +844,7 @@ func TestSortedArray_Iterator(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
index := 0 index := 0
array.IteratorAsc(func(k int, v interface{}) bool { array.IteratorAsc(func(k int, v any) bool {
index++ index++
return false return false
}) })
@ -852,7 +852,7 @@ func TestSortedArray_Iterator(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
index := 0 index := 0
array.IteratorDesc(func(k int, v interface{}) bool { array.IteratorDesc(func(k int, v any) bool {
index++ index++
return false return false
}) })
@ -913,25 +913,25 @@ func TestSortedArray_Filter(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
values := g.Slice{0, 1, 2, 3, 4, "", g.Slice{}} values := g.Slice{0, 1, 2, 3, 4, "", g.Slice{}}
array := garray.NewSortedArrayFromCopy(values, gutil.ComparatorInt) array := garray.NewSortedArrayFromCopy(values, gutil.ComparatorInt)
t.Assert(array.Filter(func(index int, value interface{}) bool { t.Assert(array.Filter(func(index int, value any) bool {
return empty.IsNil(value) return empty.IsNil(value)
}).Slice(), g.Slice{0, "", g.Slice{}, 1, 2, 3, 4}) }).Slice(), g.Slice{0, "", g.Slice{}, 1, 2, 3, 4})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewSortedArrayFromCopy(g.Slice{nil, 1, 2, 3, 4, nil}, gutil.ComparatorInt) array := garray.NewSortedArrayFromCopy(g.Slice{nil, 1, 2, 3, 4, nil}, gutil.ComparatorInt)
t.Assert(array.Filter(func(index int, value interface{}) bool { t.Assert(array.Filter(func(index int, value any) bool {
return empty.IsNil(value) return empty.IsNil(value)
}), g.Slice{1, 2, 3, 4}) }), g.Slice{1, 2, 3, 4})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewSortedArrayFrom(g.Slice{0, 1, 2, 3, 4, "", g.Slice{}}, gutil.ComparatorInt) array := garray.NewSortedArrayFrom(g.Slice{0, 1, 2, 3, 4, "", g.Slice{}}, gutil.ComparatorInt)
t.Assert(array.Filter(func(index int, value interface{}) bool { t.Assert(array.Filter(func(index int, value any) bool {
return empty.IsEmpty(value) return empty.IsEmpty(value)
}), g.Slice{1, 2, 3, 4}) }), g.Slice{1, 2, 3, 4})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3, 4}, gutil.ComparatorInt) array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3, 4}, gutil.ComparatorInt)
t.Assert(array.Filter(func(index int, value interface{}) bool { t.Assert(array.Filter(func(index int, value any) bool {
return empty.IsEmpty(value) return empty.IsEmpty(value)
}), g.Slice{1, 2, 3, 4}) }), g.Slice{1, 2, 3, 4})
}) })
@ -963,7 +963,7 @@ func TestSortedArray_FilterEmpty(t *testing.T) {
func TestSortedArray_Walk(t *testing.T) { func TestSortedArray_Walk(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewSortedArrayFrom(g.Slice{"1", "2"}, gutil.ComparatorString) array := garray.NewSortedArrayFrom(g.Slice{"1", "2"}, gutil.ComparatorString)
t.Assert(array.Walk(func(value interface{}) interface{} { t.Assert(array.Walk(func(value any) any {
return "key-" + gconv.String(value) return "key-" + gconv.String(value)
}), g.Slice{"key-1", "key-2"}) }), g.Slice{"key-1", "key-2"})
}) })
@ -971,14 +971,14 @@ func TestSortedArray_Walk(t *testing.T) {
func TestSortedArray_IsEmpty(t *testing.T) { func TestSortedArray_IsEmpty(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewSortedArrayFrom([]interface{}{}, gutil.ComparatorString) array := garray.NewSortedArrayFrom([]any{}, gutil.ComparatorString)
t.Assert(array.IsEmpty(), true) t.Assert(array.IsEmpty(), true)
}) })
} }
func TestSortedArray_DeepCopy(t *testing.T) { func TestSortedArray_DeepCopy(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
array := garray.NewSortedArrayFrom([]interface{}{1, 2, 3, 4, 5}, gutil.ComparatorString) array := garray.NewSortedArrayFrom([]any{1, 2, 3, 4, 5}, gutil.ComparatorString)
copyArray := array.DeepCopy().(*garray.SortedArray) copyArray := array.DeepCopy().(*garray.SortedArray)
array.Add(6) array.Add(6)
copyArray.Add(7) copyArray.Add(7)

View File

@ -573,7 +573,7 @@ func TestSortedIntArray_RLockFunc(t *testing.T) {
func TestSortedIntArray_Merge(t *testing.T) { func TestSortedIntArray_Merge(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
if gconv.Int(v1) < gconv.Int(v2) { if gconv.Int(v1) < gconv.Int(v2) {
return 0 return 0
} }
@ -582,9 +582,9 @@ func TestSortedIntArray_Merge(t *testing.T) {
i0 := []int{1, 2, 3, 4} i0 := []int{1, 2, 3, 4}
s2 := []string{"e", "f"} s2 := []string{"e", "f"}
i1 := garray.NewIntArrayFrom([]int{1, 2, 3}) i1 := garray.NewIntArrayFrom([]int{1, 2, 3})
i2 := garray.NewArrayFrom([]interface{}{3}) i2 := garray.NewArrayFrom([]any{3})
s3 := garray.NewStrArrayFrom([]string{"g", "h"}) s3 := garray.NewStrArrayFrom([]string{"g", "h"})
s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1)
s5 := garray.NewSortedStrArrayFrom(s2) s5 := garray.NewSortedStrArrayFrom(s2)
s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3})
a1 := garray.NewSortedIntArrayFrom(i0) a1 := garray.NewSortedIntArrayFrom(i0)

View File

@ -581,7 +581,7 @@ func TestSortedStrArray_RLockFunc(t *testing.T) {
func TestSortedStrArray_Merge(t *testing.T) { func TestSortedStrArray_Merge(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
func1 := func(v1, v2 interface{}) int { func1 := func(v1, v2 any) int {
if gconv.Int(v1) < gconv.Int(v2) { if gconv.Int(v1) < gconv.Int(v2) {
return 0 return 0
} }
@ -591,9 +591,9 @@ func TestSortedStrArray_Merge(t *testing.T) {
s1 := []string{"a", "b", "c", "d"} s1 := []string{"a", "b", "c", "d"}
s2 := []string{"e", "f"} s2 := []string{"e", "f"}
i1 := garray.NewIntArrayFrom([]int{1, 2, 3}) i1 := garray.NewIntArrayFrom([]int{1, 2, 3})
i2 := garray.NewArrayFrom([]interface{}{3}) i2 := garray.NewArrayFrom([]any{3})
s3 := garray.NewStrArrayFrom([]string{"g", "h"}) s3 := garray.NewStrArrayFrom([]string{"g", "h"})
s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1)
s5 := garray.NewSortedStrArrayFrom(s2) s5 := garray.NewSortedStrArrayFrom(s2)
s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3})
a1 := garray.NewSortedStrArrayFrom(s1) a1 := garray.NewSortedStrArrayFrom(s1)

View File

@ -41,7 +41,7 @@ func New(safe ...bool) *List {
// NewFrom creates and returns a list from a copy of given slice `array`. // NewFrom creates and returns a list from a copy of given slice `array`.
// The parameter `safe` is used to specify whether using list in concurrent-safety, // The parameter `safe` is used to specify whether using list in concurrent-safety,
// which is false in default. // which is false in default.
func NewFrom(array []interface{}, safe ...bool) *List { func NewFrom(array []any, safe ...bool) *List {
l := list.New() l := list.New()
for _, v := range array { for _, v := range array {
l.PushBack(v) l.PushBack(v)
@ -53,7 +53,7 @@ func NewFrom(array []interface{}, safe ...bool) *List {
} }
// PushFront inserts a new element `e` with value `v` at the front of list `l` and returns `e`. // PushFront inserts a new element `e` with value `v` at the front of list `l` and returns `e`.
func (l *List) PushFront(v interface{}) (e *Element) { func (l *List) PushFront(v any) (e *Element) {
l.mu.Lock() l.mu.Lock()
if l.list == nil { if l.list == nil {
l.list = list.New() l.list = list.New()
@ -64,7 +64,7 @@ func (l *List) PushFront(v interface{}) (e *Element) {
} }
// PushBack inserts a new element `e` with value `v` at the back of list `l` and returns `e`. // PushBack inserts a new element `e` with value `v` at the back of list `l` and returns `e`.
func (l *List) PushBack(v interface{}) (e *Element) { func (l *List) PushBack(v any) (e *Element) {
l.mu.Lock() l.mu.Lock()
if l.list == nil { if l.list == nil {
l.list = list.New() l.list = list.New()
@ -75,7 +75,7 @@ func (l *List) PushBack(v interface{}) (e *Element) {
} }
// PushFronts inserts multiple new elements with values `values` at the front of list `l`. // PushFronts inserts multiple new elements with values `values` at the front of list `l`.
func (l *List) PushFronts(values []interface{}) { func (l *List) PushFronts(values []any) {
l.mu.Lock() l.mu.Lock()
if l.list == nil { if l.list == nil {
l.list = list.New() l.list = list.New()
@ -87,7 +87,7 @@ func (l *List) PushFronts(values []interface{}) {
} }
// PushBacks inserts multiple new elements with values `values` at the back of list `l`. // PushBacks inserts multiple new elements with values `values` at the back of list `l`.
func (l *List) PushBacks(values []interface{}) { func (l *List) PushBacks(values []any) {
l.mu.Lock() l.mu.Lock()
if l.list == nil { if l.list == nil {
l.list = list.New() l.list = list.New()
@ -99,7 +99,7 @@ func (l *List) PushBacks(values []interface{}) {
} }
// PopBack removes the element from back of `l` and returns the value of the element. // PopBack removes the element from back of `l` and returns the value of the element.
func (l *List) PopBack() (value interface{}) { func (l *List) PopBack() (value any) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
if l.list == nil { if l.list == nil {
@ -113,7 +113,7 @@ func (l *List) PopBack() (value interface{}) {
} }
// PopFront removes the element from front of `l` and returns the value of the element. // PopFront removes the element from front of `l` and returns the value of the element.
func (l *List) PopFront() (value interface{}) { func (l *List) PopFront() (value any) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
if l.list == nil { if l.list == nil {
@ -128,7 +128,7 @@ func (l *List) PopFront() (value interface{}) {
// PopBacks removes `max` elements from back of `l` // PopBacks removes `max` elements from back of `l`
// and returns values of the removed elements as slice. // and returns values of the removed elements as slice.
func (l *List) PopBacks(max int) (values []interface{}) { func (l *List) PopBacks(max int) (values []any) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
if l.list == nil { if l.list == nil {
@ -140,7 +140,7 @@ func (l *List) PopBacks(max int) (values []interface{}) {
if max > 0 && max < length { if max > 0 && max < length {
length = max length = max
} }
values = make([]interface{}, length) values = make([]any, length)
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
values[i] = l.list.Remove(l.list.Back()) values[i] = l.list.Remove(l.list.Back())
} }
@ -150,7 +150,7 @@ func (l *List) PopBacks(max int) (values []interface{}) {
// PopFronts removes `max` elements from front of `l` // PopFronts removes `max` elements from front of `l`
// and returns values of the removed elements as slice. // and returns values of the removed elements as slice.
func (l *List) PopFronts(max int) (values []interface{}) { func (l *List) PopFronts(max int) (values []any) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
if l.list == nil { if l.list == nil {
@ -162,7 +162,7 @@ func (l *List) PopFronts(max int) (values []interface{}) {
if max > 0 && max < length { if max > 0 && max < length {
length = max length = max
} }
values = make([]interface{}, length) values = make([]any, length)
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
values[i] = l.list.Remove(l.list.Front()) values[i] = l.list.Remove(l.list.Front())
} }
@ -172,18 +172,18 @@ func (l *List) PopFronts(max int) (values []interface{}) {
// PopBackAll removes all elements from back of `l` // PopBackAll removes all elements from back of `l`
// and returns values of the removed elements as slice. // and returns values of the removed elements as slice.
func (l *List) PopBackAll() []interface{} { func (l *List) PopBackAll() []any {
return l.PopBacks(-1) return l.PopBacks(-1)
} }
// PopFrontAll removes all elements from front of `l` // PopFrontAll removes all elements from front of `l`
// and returns values of the removed elements as slice. // and returns values of the removed elements as slice.
func (l *List) PopFrontAll() []interface{} { func (l *List) PopFrontAll() []any {
return l.PopFronts(-1) return l.PopFronts(-1)
} }
// FrontAll copies and returns values of all elements from front of `l` as slice. // FrontAll copies and returns values of all elements from front of `l` as slice.
func (l *List) FrontAll() (values []interface{}) { func (l *List) FrontAll() (values []any) {
l.mu.RLock() l.mu.RLock()
defer l.mu.RUnlock() defer l.mu.RUnlock()
if l.list == nil { if l.list == nil {
@ -191,7 +191,7 @@ func (l *List) FrontAll() (values []interface{}) {
} }
length := l.list.Len() length := l.list.Len()
if length > 0 { if length > 0 {
values = make([]interface{}, length) values = make([]any, length)
for i, e := 0, l.list.Front(); i < length; i, e = i+1, e.Next() { for i, e := 0, l.list.Front(); i < length; i, e = i+1, e.Next() {
values[i] = e.Value values[i] = e.Value
} }
@ -200,7 +200,7 @@ func (l *List) FrontAll() (values []interface{}) {
} }
// BackAll copies and returns values of all elements from back of `l` as slice. // BackAll copies and returns values of all elements from back of `l` as slice.
func (l *List) BackAll() (values []interface{}) { func (l *List) BackAll() (values []any) {
l.mu.RLock() l.mu.RLock()
defer l.mu.RUnlock() defer l.mu.RUnlock()
if l.list == nil { if l.list == nil {
@ -208,7 +208,7 @@ func (l *List) BackAll() (values []interface{}) {
} }
length := l.list.Len() length := l.list.Len()
if length > 0 { if length > 0 {
values = make([]interface{}, length) values = make([]any, length)
for i, e := 0, l.list.Back(); i < length; i, e = i+1, e.Prev() { for i, e := 0, l.list.Back(); i < length; i, e = i+1, e.Prev() {
values[i] = e.Value values[i] = e.Value
} }
@ -217,7 +217,7 @@ func (l *List) BackAll() (values []interface{}) {
} }
// FrontValue returns value of the first element of `l` or nil if the list is empty. // FrontValue returns value of the first element of `l` or nil if the list is empty.
func (l *List) FrontValue() (value interface{}) { func (l *List) FrontValue() (value any) {
l.mu.RLock() l.mu.RLock()
defer l.mu.RUnlock() defer l.mu.RUnlock()
if l.list == nil { if l.list == nil {
@ -230,7 +230,7 @@ func (l *List) FrontValue() (value interface{}) {
} }
// BackValue returns value of the last element of `l` or nil if the list is empty. // BackValue returns value of the last element of `l` or nil if the list is empty.
func (l *List) BackValue() (value interface{}) { func (l *List) BackValue() (value any) {
l.mu.RLock() l.mu.RLock()
defer l.mu.RUnlock() defer l.mu.RUnlock()
if l.list == nil { if l.list == nil {
@ -362,7 +362,7 @@ func (l *List) PushFrontList(other *List) {
// InsertAfter inserts a new element `e` with value `v` immediately after `p` and returns `e`. // InsertAfter inserts a new element `e` with value `v` immediately after `p` and returns `e`.
// If `p` is not an element of `l`, the list is not modified. // If `p` is not an element of `l`, the list is not modified.
// The `p` must not be nil. // The `p` must not be nil.
func (l *List) InsertAfter(p *Element, v interface{}) (e *Element) { func (l *List) InsertAfter(p *Element, v any) (e *Element) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
if l.list == nil { if l.list == nil {
@ -375,7 +375,7 @@ func (l *List) InsertAfter(p *Element, v interface{}) (e *Element) {
// InsertBefore inserts a new element `e` with value `v` immediately before `p` and returns `e`. // InsertBefore inserts a new element `e` with value `v` immediately before `p` and returns `e`.
// If `p` is not an element of `l`, the list is not modified. // If `p` is not an element of `l`, the list is not modified.
// The `p` must not be nil. // The `p` must not be nil.
func (l *List) InsertBefore(p *Element, v interface{}) (e *Element) { func (l *List) InsertBefore(p *Element, v any) (e *Element) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
if l.list == nil { if l.list == nil {
@ -388,7 +388,7 @@ func (l *List) InsertBefore(p *Element, v interface{}) (e *Element) {
// Remove removes `e` from `l` if `e` is an element of list `l`. // Remove removes `e` from `l` if `e` is an element of list `l`.
// It returns the element value e.Value. // It returns the element value e.Value.
// The element must not be nil. // The element must not be nil.
func (l *List) Remove(e *Element) (value interface{}) { func (l *List) Remove(e *Element) (value any) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
if l.list == nil { if l.list == nil {
@ -522,7 +522,7 @@ func (l *List) UnmarshalJSON(b []byte) error {
if l.list == nil { if l.list == nil {
l.list = list.New() l.list = list.New()
} }
var array []interface{} var array []any
if err := json.UnmarshalUseNumber(b, &array); err != nil { if err := json.UnmarshalUseNumber(b, &array); err != nil {
return err return err
} }
@ -531,13 +531,13 @@ func (l *List) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for list. // UnmarshalValue is an interface implement which sets any type of value for list.
func (l *List) UnmarshalValue(value interface{}) (err error) { func (l *List) UnmarshalValue(value any) (err error) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
if l.list == nil { if l.list == nil {
l.list = list.New() l.list = list.New()
} }
var array []interface{} var array []any
switch value.(type) { switch value.(type) {
case string, []byte: case string, []byte:
err = json.UnmarshalUseNumber(gconv.Bytes(value), &array) err = json.UnmarshalUseNumber(gconv.Bytes(value), &array)
@ -549,7 +549,7 @@ func (l *List) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (l *List) DeepCopy() interface{} { func (l *List) DeepCopy() any {
if l == nil { if l == nil {
return nil return nil
} }
@ -562,7 +562,7 @@ func (l *List) DeepCopy() interface{} {
} }
var ( var (
length = l.list.Len() length = l.list.Len()
values = make([]interface{}, length) values = make([]any, length)
) )
if length > 0 { if length > 0 {
for i, e := 0, l.list.Front(); i < length; i, e = i+1, e.Next() { for i, e := 0, l.list.Front(); i < length; i, e = i+1, e.Next() {

View File

@ -198,7 +198,7 @@ func TestList(t *testing.T) {
}) })
} }
func checkList(t *gtest.T, l *List, es []interface{}) { func checkList(t *gtest.T, l *List, es []any) {
if !checkListLen(t, l, len(es)) { if !checkListLen(t, l, len(es)) {
return return
} }
@ -244,36 +244,36 @@ func TestExtending(t *testing.T) {
l3 := New() l3 := New()
l3.PushBackList(l1) l3.PushBackList(l1)
checkList(t, l3, []interface{}{1, 2, 3}) checkList(t, l3, []any{1, 2, 3})
l3.PushBackList(l2) l3.PushBackList(l2)
checkList(t, l3, []interface{}{1, 2, 3, 4, 5}) checkList(t, l3, []any{1, 2, 3, 4, 5})
l3 = New() l3 = New()
l3.PushFrontList(l2) l3.PushFrontList(l2)
checkList(t, l3, []interface{}{4, 5}) checkList(t, l3, []any{4, 5})
l3.PushFrontList(l1) l3.PushFrontList(l1)
checkList(t, l3, []interface{}{1, 2, 3, 4, 5}) checkList(t, l3, []any{1, 2, 3, 4, 5})
checkList(t, l1, []interface{}{1, 2, 3}) checkList(t, l1, []any{1, 2, 3})
checkList(t, l2, []interface{}{4, 5}) checkList(t, l2, []any{4, 5})
l3 = New() l3 = New()
l3.PushBackList(l1) l3.PushBackList(l1)
checkList(t, l3, []interface{}{1, 2, 3}) checkList(t, l3, []any{1, 2, 3})
l3.PushBackList(l3) l3.PushBackList(l3)
checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3}) checkList(t, l3, []any{1, 2, 3, 1, 2, 3})
l3 = New() l3 = New()
l3.PushFrontList(l1) l3.PushFrontList(l1)
checkList(t, l3, []interface{}{1, 2, 3}) checkList(t, l3, []any{1, 2, 3})
l3.PushFrontList(l3) l3.PushFrontList(l3)
checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3}) checkList(t, l3, []any{1, 2, 3, 1, 2, 3})
l3 = New() l3 = New()
l1.PushBackList(l3) l1.PushBackList(l3)
checkList(t, l1, []interface{}{1, 2, 3}) checkList(t, l1, []any{1, 2, 3})
l1.PushFrontList(l3) l1.PushFrontList(l3)
checkList(t, l1, []interface{}{1, 2, 3}) checkList(t, l1, []any{1, 2, 3})
}) })
} }
@ -371,19 +371,19 @@ func TestZeroList(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var l1 = New() var l1 = New()
l1.PushFront(1) l1.PushFront(1)
checkList(t, l1, []interface{}{1}) checkList(t, l1, []any{1})
var l2 = New() var l2 = New()
l2.PushBack(1) l2.PushBack(1)
checkList(t, l2, []interface{}{1}) checkList(t, l2, []any{1})
var l3 = New() var l3 = New()
l3.PushFrontList(l1) l3.PushFrontList(l1)
checkList(t, l3, []interface{}{1}) checkList(t, l3, []any{1})
var l4 = New() var l4 = New()
l4.PushBackList(l2) l4.PushBackList(l2)
checkList(t, l4, []interface{}{1}) checkList(t, l4, []any{1})
}) })
} }
@ -395,7 +395,7 @@ func TestInsertBeforeUnknownMark(t *testing.T) {
l.PushBack(2) l.PushBack(2)
l.PushBack(3) l.PushBack(3)
l.InsertBefore(new(Element), 1) l.InsertBefore(new(Element), 1)
checkList(t, l, []interface{}{1, 2, 3}) checkList(t, l, []any{1, 2, 3})
}) })
} }
@ -407,7 +407,7 @@ func TestInsertAfterUnknownMark(t *testing.T) {
l.PushBack(2) l.PushBack(2)
l.PushBack(3) l.PushBack(3)
l.InsertAfter(new(Element), 1) l.InsertAfter(new(Element), 1)
checkList(t, l, []interface{}{1, 2, 3}) checkList(t, l, []any{1, 2, 3})
}) })
} }
@ -421,12 +421,12 @@ func TestMoveUnknownMark(t *testing.T) {
e2 := l2.PushBack(2) e2 := l2.PushBack(2)
l1.MoveAfter(e1, e2) l1.MoveAfter(e1, e2)
checkList(t, l1, []interface{}{1}) checkList(t, l1, []any{1})
checkList(t, l2, []interface{}{2}) checkList(t, l2, []any{2})
l1.MoveBefore(e1, e2) l1.MoveBefore(e1, e2)
checkList(t, l1, []interface{}{1}) checkList(t, l1, []any{1})
checkList(t, l2, []interface{}{2}) checkList(t, l2, []any{2})
}) })
} }
@ -435,58 +435,58 @@ func TestList_RemoveAll(t *testing.T) {
l := New() l := New()
l.PushBack(1) l.PushBack(1)
l.RemoveAll() l.RemoveAll()
checkList(t, l, []interface{}{}) checkList(t, l, []any{})
l.PushBack(2) l.PushBack(2)
checkList(t, l, []interface{}{2}) checkList(t, l, []any{2})
}) })
} }
func TestList_PushFronts(t *testing.T) { func TestList_PushFronts(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2} a1 := []any{1, 2}
l.PushFronts(a1) l.PushFronts(a1)
checkList(t, l, []interface{}{2, 1}) checkList(t, l, []any{2, 1})
a1 = []interface{}{3, 4, 5} a1 = []any{3, 4, 5}
l.PushFronts(a1) l.PushFronts(a1)
checkList(t, l, []interface{}{5, 4, 3, 2, 1}) checkList(t, l, []any{5, 4, 3, 2, 1})
}) })
} }
func TestList_PushBacks(t *testing.T) { func TestList_PushBacks(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2} a1 := []any{1, 2}
l.PushBacks(a1) l.PushBacks(a1)
checkList(t, l, []interface{}{1, 2}) checkList(t, l, []any{1, 2})
a1 = []interface{}{3, 4, 5} a1 = []any{3, 4, 5}
l.PushBacks(a1) l.PushBacks(a1)
checkList(t, l, []interface{}{1, 2, 3, 4, 5}) checkList(t, l, []any{1, 2, 3, 4, 5})
}) })
} }
func TestList_PopBacks(t *testing.T) { func TestList_PopBacks(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
a2 := []interface{}{"a", "c", "b", "e"} a2 := []any{"a", "c", "b", "e"}
l.PushFronts(a1) l.PushFronts(a1)
i1 := l.PopBacks(2) i1 := l.PopBacks(2)
t.Assert(i1, []interface{}{1, 2}) t.Assert(i1, []any{1, 2})
l.PushBacks(a2) // 4.3,a,c,b,e l.PushBacks(a2) // 4.3,a,c,b,e
i1 = l.PopBacks(3) i1 = l.PopBacks(3)
t.Assert(i1, []interface{}{"e", "b", "c"}) t.Assert(i1, []any{"e", "b", "c"})
}) })
} }
func TestList_PopFronts(t *testing.T) { func TestList_PopFronts(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
i1 := l.PopFronts(2) i1 := l.PopFronts(2)
t.Assert(i1, []interface{}{4, 3}) t.Assert(i1, []any{4, 3})
t.Assert(l.Len(), 2) t.Assert(l.Len(), 2)
}) })
} }
@ -494,10 +494,10 @@ func TestList_PopFronts(t *testing.T) {
func TestList_PopBackAll(t *testing.T) { func TestList_PopBackAll(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
i1 := l.PopBackAll() i1 := l.PopBackAll()
t.Assert(i1, []interface{}{1, 2, 3, 4}) t.Assert(i1, []any{1, 2, 3, 4})
t.Assert(l.Len(), 0) t.Assert(l.Len(), 0)
}) })
} }
@ -505,10 +505,10 @@ func TestList_PopBackAll(t *testing.T) {
func TestList_PopFrontAll(t *testing.T) { func TestList_PopFrontAll(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
i1 := l.PopFrontAll() i1 := l.PopFrontAll()
t.Assert(i1, []interface{}{4, 3, 2, 1}) t.Assert(i1, []any{4, 3, 2, 1})
t.Assert(l.Len(), 0) t.Assert(l.Len(), 0)
}) })
} }
@ -516,10 +516,10 @@ func TestList_PopFrontAll(t *testing.T) {
func TestList_FrontAll(t *testing.T) { func TestList_FrontAll(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
i1 := l.FrontAll() i1 := l.FrontAll()
t.Assert(i1, []interface{}{4, 3, 2, 1}) t.Assert(i1, []any{4, 3, 2, 1})
t.Assert(l.Len(), 4) t.Assert(l.Len(), 4)
}) })
} }
@ -527,10 +527,10 @@ func TestList_FrontAll(t *testing.T) {
func TestList_BackAll(t *testing.T) { func TestList_BackAll(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
i1 := l.BackAll() i1 := l.BackAll()
t.Assert(i1, []interface{}{1, 2, 3, 4}) t.Assert(i1, []any{1, 2, 3, 4})
t.Assert(l.Len(), 4) t.Assert(l.Len(), 4)
}) })
} }
@ -539,7 +539,7 @@ func TestList_FrontValue(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
l2 := New() l2 := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
i1 := l.FrontValue() i1 := l.FrontValue()
t.Assert(gconv.Int(i1), 4) t.Assert(gconv.Int(i1), 4)
@ -554,7 +554,7 @@ func TestList_BackValue(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
l2 := New() l2 := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
i1 := l.BackValue() i1 := l.BackValue()
t.Assert(gconv.Int(i1), 1) t.Assert(gconv.Int(i1), 1)
@ -568,7 +568,7 @@ func TestList_BackValue(t *testing.T) {
func TestList_Back(t *testing.T) { func TestList_Back(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
e1 := l.Back() e1 := l.Back()
t.Assert(e1.Value, 1) t.Assert(e1.Value, 1)
@ -579,7 +579,7 @@ func TestList_Back(t *testing.T) {
func TestList_Size(t *testing.T) { func TestList_Size(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
t.Assert(l.Size(), 4) t.Assert(l.Size(), 4)
l.PopFront() l.PopFront()
@ -590,7 +590,7 @@ func TestList_Size(t *testing.T) {
func TestList_Removes(t *testing.T) { func TestList_Removes(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
e1 := l.Back() e1 := l.Back()
l.Removes([]*Element{e1}) l.Removes([]*Element{e1})
@ -599,25 +599,25 @@ func TestList_Removes(t *testing.T) {
e2 := l.Back() e2 := l.Back()
l.Removes([]*Element{e2}) l.Removes([]*Element{e2})
t.Assert(l.Len(), 2) t.Assert(l.Len(), 2)
checkList(t, l, []interface{}{4, 3}) checkList(t, l, []any{4, 3})
}) })
} }
func TestList_Pop(t *testing.T) { func TestList_Pop(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) l := NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9})
t.Assert(l.PopBack(), 9) t.Assert(l.PopBack(), 9)
t.Assert(l.PopBacks(2), []interface{}{8, 7}) t.Assert(l.PopBacks(2), []any{8, 7})
t.Assert(l.PopFront(), 1) t.Assert(l.PopFront(), 1)
t.Assert(l.PopFronts(2), []interface{}{2, 3}) t.Assert(l.PopFronts(2), []any{2, 3})
}) })
} }
func TestList_Clear(t *testing.T) { func TestList_Clear(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
l.Clear() l.Clear()
t.Assert(l.Len(), 0) t.Assert(l.Len(), 0)
@ -627,22 +627,22 @@ func TestList_Clear(t *testing.T) {
func TestList_IteratorAsc(t *testing.T) { func TestList_IteratorAsc(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 5, 6, 3, 4} a1 := []any{1, 2, 5, 6, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
e1 := l.Back() e1 := l.Back()
fun1 := func(e *Element) bool { fun1 := func(e *Element) bool {
return gconv.Int(e1.Value) > 2 return gconv.Int(e1.Value) > 2
} }
checkList(t, l, []interface{}{4, 3, 6, 5, 2, 1}) checkList(t, l, []any{4, 3, 6, 5, 2, 1})
l.IteratorAsc(fun1) l.IteratorAsc(fun1)
checkList(t, l, []interface{}{4, 3, 6, 5, 2, 1}) checkList(t, l, []any{4, 3, 6, 5, 2, 1})
}) })
} }
func TestList_IteratorDesc(t *testing.T) { func TestList_IteratorDesc(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{1, 2, 3, 4} a1 := []any{1, 2, 3, 4}
l.PushFronts(a1) l.PushFronts(a1)
e1 := l.Back() e1 := l.Back()
fun1 := func(e *Element) bool { fun1 := func(e *Element) bool {
@ -650,28 +650,28 @@ func TestList_IteratorDesc(t *testing.T) {
} }
l.IteratorDesc(fun1) l.IteratorDesc(fun1)
t.Assert(l.Len(), 4) t.Assert(l.Len(), 4)
checkList(t, l, []interface{}{4, 3, 2, 1}) checkList(t, l, []any{4, 3, 2, 1})
}) })
} }
func TestList_Iterator(t *testing.T) { func TestList_Iterator(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := New() l := New()
a1 := []interface{}{"a", "b", "c", "d", "e"} a1 := []any{"a", "b", "c", "d", "e"}
l.PushFronts(a1) l.PushFronts(a1)
e1 := l.Back() e1 := l.Back()
fun1 := func(e *Element) bool { fun1 := func(e *Element) bool {
return gconv.String(e1.Value) > "c" return gconv.String(e1.Value) > "c"
} }
checkList(t, l, []interface{}{"e", "d", "c", "b", "a"}) checkList(t, l, []any{"e", "d", "c", "b", "a"})
l.Iterator(fun1) l.Iterator(fun1)
checkList(t, l, []interface{}{"e", "d", "c", "b", "a"}) checkList(t, l, []any{"e", "d", "c", "b", "a"})
}) })
} }
func TestList_Join(t *testing.T) { func TestList_Join(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := NewFrom([]interface{}{1, 2, "a", `"b"`, `\c`}) l := NewFrom([]any{1, 2, "a", `"b"`, `\c`})
t.Assert(l.Join(","), `1,2,a,"b",\c`) t.Assert(l.Join(","), `1,2,a,"b",\c`)
t.Assert(l.Join("."), `1.2.a."b".\c`) t.Assert(l.Join("."), `1.2.a."b".\c`)
}) })
@ -679,7 +679,7 @@ func TestList_Join(t *testing.T) {
func TestList_String(t *testing.T) { func TestList_String(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := NewFrom([]interface{}{1, 2, "a", `"b"`, `\c`}) l := NewFrom([]any{1, 2, "a", `"b"`, `\c`})
t.Assert(l.String(), `[1,2,a,"b",\c]`) t.Assert(l.String(), `[1,2,a,"b",\c]`)
}) })
} }
@ -687,7 +687,7 @@ func TestList_String(t *testing.T) {
func TestList_Json(t *testing.T) { func TestList_Json(t *testing.T) {
// Marshal // Marshal
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a := []interface{}{"a", "b", "c"} a := []any{"a", "b", "c"}
l := New() l := New()
l.PushBacks(a) l.PushBacks(a)
b1, err1 := json.Marshal(l) b1, err1 := json.Marshal(l)
@ -697,7 +697,7 @@ func TestList_Json(t *testing.T) {
}) })
// Unmarshal // Unmarshal
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
a := []interface{}{"a", "b", "c"} a := []any{"a", "b", "c"}
l := New() l := New()
b, err := json.Marshal(a) b, err := json.Marshal(a)
t.AssertNil(err) t.AssertNil(err)
@ -708,7 +708,7 @@ func TestList_Json(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var l List var l List
a := []interface{}{"a", "b", "c"} a := []any{"a", "b", "c"}
b, err := json.Marshal(a) b, err := json.Marshal(a)
t.AssertNil(err) t.AssertNil(err)
@ -726,30 +726,30 @@ func TestList_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var tlist *TList var tlist *TList
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"list": []byte(`[1,2,3]`), "list": []byte(`[1,2,3]`),
}, &tlist) }, &tlist)
t.AssertNil(err) t.AssertNil(err)
t.Assert(tlist.Name, "john") t.Assert(tlist.Name, "john")
t.Assert(tlist.List.FrontAll(), []interface{}{1, 2, 3}) t.Assert(tlist.List.FrontAll(), []any{1, 2, 3})
}) })
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var tlist *TList var tlist *TList
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"list": []interface{}{1, 2, 3}, "list": []any{1, 2, 3},
}, &tlist) }, &tlist)
t.AssertNil(err) t.AssertNil(err)
t.Assert(tlist.Name, "john") t.Assert(tlist.Name, "john")
t.Assert(tlist.List.FrontAll(), []interface{}{1, 2, 3}) t.Assert(tlist.List.FrontAll(), []any{1, 2, 3})
}) })
} }
func TestList_DeepCopy(t *testing.T) { func TestList_DeepCopy(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
l := NewFrom([]interface{}{1, 2, "a", `"b"`, `\c`}) l := NewFrom([]any{1, 2, "a", `"b"`, `\c`})
copyList := l.DeepCopy() copyList := l.DeepCopy()
cl := copyList.(*List) cl := copyList.(*List)
cl.PopBack() cl.PopBack()

View File

@ -24,7 +24,7 @@ func New(safe ...bool) *Map {
// there might be some concurrent-safe issues when changing the map outside. // there might be some concurrent-safe issues when changing the map outside.
// The parameter `safe` is used to specify whether using tree in concurrent-safety, // The parameter `safe` is used to specify whether using tree in concurrent-safety,
// which is false in default. // which is false in default.
func NewFrom(data map[interface{}]interface{}, safe ...bool) *Map { func NewFrom(data map[any]any, safe ...bool) *Map {
return NewAnyAnyMapFrom(data, safe...) return NewAnyAnyMapFrom(data, safe...)
} }
@ -40,6 +40,6 @@ func NewHashMap(safe ...bool) *Map {
// there might be some concurrent-safe issues when changing the map outside. // there might be some concurrent-safe issues when changing the map outside.
// The parameter `safe` is used to specify whether using tree in concurrent-safety, // The parameter `safe` is used to specify whether using tree in concurrent-safety,
// which is false in default. // which is false in default.
func NewHashMapFrom(data map[interface{}]interface{}, safe ...bool) *Map { func NewHashMapFrom(data map[any]any, safe ...bool) *Map {
return NewAnyAnyMapFrom(data, safe...) return NewAnyAnyMapFrom(data, safe...)
} }

View File

@ -17,10 +17,10 @@ import (
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
) )
// AnyAnyMap wraps map type `map[interface{}]interface{}` and provides more map features. // AnyAnyMap wraps map type `map[any]any` and provides more map features.
type AnyAnyMap struct { type AnyAnyMap struct {
mu rwmutex.RWMutex mu rwmutex.RWMutex
data map[interface{}]interface{} data map[any]any
} }
// NewAnyAnyMap creates and returns an empty hash map. // NewAnyAnyMap creates and returns an empty hash map.
@ -29,14 +29,14 @@ type AnyAnyMap struct {
func NewAnyAnyMap(safe ...bool) *AnyAnyMap { func NewAnyAnyMap(safe ...bool) *AnyAnyMap {
return &AnyAnyMap{ return &AnyAnyMap{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
data: make(map[interface{}]interface{}), data: make(map[any]any),
} }
} }
// NewAnyAnyMapFrom creates and returns a hash map from given map `data`. // NewAnyAnyMapFrom creates and returns a hash map from given map `data`.
// Note that, the param `data` map will be set as the underlying data map(no deep copy), // Note that, the param `data` map will be set as the underlying data map(no deep copy),
// there might be some concurrent-safe issues when changing the map outside. // there might be some concurrent-safe issues when changing the map outside.
func NewAnyAnyMapFrom(data map[interface{}]interface{}, safe ...bool) *AnyAnyMap { func NewAnyAnyMapFrom(data map[any]any, safe ...bool) *AnyAnyMap {
return &AnyAnyMap{ return &AnyAnyMap{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
data: data, data: data,
@ -45,7 +45,7 @@ func NewAnyAnyMapFrom(data map[interface{}]interface{}, safe ...bool) *AnyAnyMap
// Iterator iterates the hash map readonly with custom callback function `f`. // Iterator iterates the hash map readonly with custom callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (m *AnyAnyMap) Iterator(f func(k interface{}, v interface{}) bool) { func (m *AnyAnyMap) Iterator(f func(k any, v any) bool) {
for k, v := range m.Map() { for k, v := range m.Map() {
if !f(k, v) { if !f(k, v) {
break break
@ -61,13 +61,13 @@ func (m *AnyAnyMap) Clone(safe ...bool) *AnyAnyMap {
// Map returns the underlying data map. // Map returns the underlying data map.
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
// or else a pointer to the underlying data. // or else a pointer to the underlying data.
func (m *AnyAnyMap) Map() map[interface{}]interface{} { func (m *AnyAnyMap) Map() map[any]any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
if !m.mu.IsSafe() { if !m.mu.IsSafe() {
return m.data return m.data
} }
data := make(map[interface{}]interface{}, len(m.data)) data := make(map[any]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = v data[k] = v
} }
@ -75,21 +75,21 @@ func (m *AnyAnyMap) Map() map[interface{}]interface{} {
} }
// MapCopy returns a shallow copy of the underlying data of the hash map. // MapCopy returns a shallow copy of the underlying data of the hash map.
func (m *AnyAnyMap) MapCopy() map[interface{}]interface{} { func (m *AnyAnyMap) MapCopy() map[any]any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[interface{}]interface{}, len(m.data)) data := make(map[any]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = v data[k] = v
} }
return data return data
} }
// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. // MapStrAny returns a copy of the underlying data of the map as map[string]any.
func (m *AnyAnyMap) MapStrAny() map[string]interface{} { func (m *AnyAnyMap) MapStrAny() map[string]any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[gconv.String(k)] = v data[gconv.String(k)] = v
} }
@ -120,17 +120,17 @@ func (m *AnyAnyMap) FilterNil() {
} }
// Set sets key-value to the hash map. // Set sets key-value to the hash map.
func (m *AnyAnyMap) Set(key interface{}, value interface{}) { func (m *AnyAnyMap) Set(key any, value any) {
m.mu.Lock() m.mu.Lock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]interface{}) m.data = make(map[any]any)
} }
m.data[key] = value m.data[key] = value
m.mu.Unlock() m.mu.Unlock()
} }
// Sets batch sets key-values to the hash map. // Sets batch sets key-values to the hash map.
func (m *AnyAnyMap) Sets(data map[interface{}]interface{}) { func (m *AnyAnyMap) Sets(data map[any]any) {
m.mu.Lock() m.mu.Lock()
if m.data == nil { if m.data == nil {
m.data = data m.data = data
@ -144,7 +144,7 @@ func (m *AnyAnyMap) Sets(data map[interface{}]interface{}) {
// Search searches the map with given `key`. // Search searches the map with given `key`.
// Second return parameter `found` is true if key was found, otherwise false. // Second return parameter `found` is true if key was found, otherwise false.
func (m *AnyAnyMap) Search(key interface{}) (value interface{}, found bool) { func (m *AnyAnyMap) Search(key any) (value any, found bool) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
value, found = m.data[key] value, found = m.data[key]
@ -154,7 +154,7 @@ func (m *AnyAnyMap) Search(key interface{}) (value interface{}, found bool) {
} }
// Get returns the value by given `key`. // Get returns the value by given `key`.
func (m *AnyAnyMap) Get(key interface{}) (value interface{}) { func (m *AnyAnyMap) Get(key any) (value any) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
value = m.data[key] value = m.data[key]
@ -164,7 +164,7 @@ func (m *AnyAnyMap) Get(key interface{}) (value interface{}) {
} }
// Pop retrieves and deletes an item from the map. // Pop retrieves and deletes an item from the map.
func (m *AnyAnyMap) Pop() (key, value interface{}) { func (m *AnyAnyMap) Pop() (key, value any) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
for key, value = range m.data { for key, value = range m.data {
@ -176,7 +176,7 @@ func (m *AnyAnyMap) Pop() (key, value interface{}) {
// Pops retrieves and deletes `size` items from the map. // Pops retrieves and deletes `size` items from the map.
// It returns all items if size == -1. // It returns all items if size == -1.
func (m *AnyAnyMap) Pops(size int) map[interface{}]interface{} { func (m *AnyAnyMap) Pops(size int) map[any]any {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if size > len(m.data) || size == -1 { if size > len(m.data) || size == -1 {
@ -187,7 +187,7 @@ func (m *AnyAnyMap) Pops(size int) map[interface{}]interface{} {
} }
var ( var (
index = 0 index = 0
newMap = make(map[interface{}]interface{}, size) newMap = make(map[any]any, size)
) )
for k, v := range m.data { for k, v := range m.data {
delete(m.data, k) delete(m.data, k)
@ -209,16 +209,16 @@ func (m *AnyAnyMap) Pops(size int) map[interface{}]interface{} {
// and its return value will be set to the map with `key`. // and its return value will be set to the map with `key`.
// //
// It returns value with given `key`. // It returns value with given `key`.
func (m *AnyAnyMap) doSetWithLockCheck(key interface{}, value interface{}) interface{} { func (m *AnyAnyMap) doSetWithLockCheck(key any, value any) any {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]interface{}) m.data = make(map[any]any)
} }
if v, ok := m.data[key]; ok { if v, ok := m.data[key]; ok {
return v return v
} }
if f, ok := value.(func() interface{}); ok { if f, ok := value.(func() any); ok {
value = f() value = f()
} }
if value != nil { if value != nil {
@ -229,7 +229,7 @@ func (m *AnyAnyMap) doSetWithLockCheck(key interface{}, value interface{}) inter
// GetOrSet returns the value by key, // GetOrSet returns the value by key,
// or sets value with given `value` if it does not exist and then returns this value. // or sets value with given `value` if it does not exist and then returns this value.
func (m *AnyAnyMap) GetOrSet(key interface{}, value interface{}) interface{} { func (m *AnyAnyMap) GetOrSet(key any, value any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, value) return m.doSetWithLockCheck(key, value)
} else { } else {
@ -240,7 +240,7 @@ func (m *AnyAnyMap) GetOrSet(key interface{}, value interface{}) interface{} {
// GetOrSetFunc returns the value by key, // GetOrSetFunc returns the value by key,
// or sets value with returned value of callback function `f` if it does not exist // or sets value with returned value of callback function `f` if it does not exist
// and then returns this value. // and then returns this value.
func (m *AnyAnyMap) GetOrSetFunc(key interface{}, f func() interface{}) interface{} { func (m *AnyAnyMap) GetOrSetFunc(key any, f func() any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, f()) return m.doSetWithLockCheck(key, f())
} else { } else {
@ -254,7 +254,7 @@ func (m *AnyAnyMap) GetOrSetFunc(key interface{}, f func() interface{}) interfac
// //
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f`
// with mutex.Lock of the hash map. // with mutex.Lock of the hash map.
func (m *AnyAnyMap) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} { func (m *AnyAnyMap) GetOrSetFuncLock(key any, f func() any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, f) return m.doSetWithLockCheck(key, f)
} else { } else {
@ -264,31 +264,31 @@ func (m *AnyAnyMap) GetOrSetFuncLock(key interface{}, f func() interface{}) inte
// GetVar returns a Var with the value by given `key`. // GetVar returns a Var with the value by given `key`.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *AnyAnyMap) GetVar(key interface{}) *gvar.Var { func (m *AnyAnyMap) GetVar(key any) *gvar.Var {
return gvar.New(m.Get(key)) return gvar.New(m.Get(key))
} }
// GetVarOrSet returns a Var with result from GetOrSet. // GetVarOrSet returns a Var with result from GetOrSet.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *AnyAnyMap) GetVarOrSet(key interface{}, value interface{}) *gvar.Var { func (m *AnyAnyMap) GetVarOrSet(key any, value any) *gvar.Var {
return gvar.New(m.GetOrSet(key, value)) return gvar.New(m.GetOrSet(key, value))
} }
// GetVarOrSetFunc returns a Var with result from GetOrSetFunc. // GetVarOrSetFunc returns a Var with result from GetOrSetFunc.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *AnyAnyMap) GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var { func (m *AnyAnyMap) GetVarOrSetFunc(key any, f func() any) *gvar.Var {
return gvar.New(m.GetOrSetFunc(key, f)) return gvar.New(m.GetOrSetFunc(key, f))
} }
// GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock. // GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *AnyAnyMap) GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var { func (m *AnyAnyMap) GetVarOrSetFuncLock(key any, f func() any) *gvar.Var {
return gvar.New(m.GetOrSetFuncLock(key, f)) return gvar.New(m.GetOrSetFuncLock(key, f))
} }
// SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true.
// It returns false if `key` exists, and `value` would be ignored. // It returns false if `key` exists, and `value` would be ignored.
func (m *AnyAnyMap) SetIfNotExist(key interface{}, value interface{}) bool { func (m *AnyAnyMap) SetIfNotExist(key any, value any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, value) m.doSetWithLockCheck(key, value)
return true return true
@ -298,7 +298,7 @@ func (m *AnyAnyMap) SetIfNotExist(key interface{}, value interface{}) bool {
// SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true.
// It returns false if `key` exists, and `value` would be ignored. // It returns false if `key` exists, and `value` would be ignored.
func (m *AnyAnyMap) SetIfNotExistFunc(key interface{}, f func() interface{}) bool { func (m *AnyAnyMap) SetIfNotExistFunc(key any, f func() any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, f()) m.doSetWithLockCheck(key, f())
return true return true
@ -311,7 +311,7 @@ func (m *AnyAnyMap) SetIfNotExistFunc(key interface{}, f func() interface{}) boo
// //
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
// it executes function `f` with mutex.Lock of the hash map. // it executes function `f` with mutex.Lock of the hash map.
func (m *AnyAnyMap) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool { func (m *AnyAnyMap) SetIfNotExistFuncLock(key any, f func() any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, f) m.doSetWithLockCheck(key, f)
return true return true
@ -320,7 +320,7 @@ func (m *AnyAnyMap) SetIfNotExistFuncLock(key interface{}, f func() interface{})
} }
// Remove deletes value from map by given `key`, and return this deleted value. // Remove deletes value from map by given `key`, and return this deleted value.
func (m *AnyAnyMap) Remove(key interface{}) (value interface{}) { func (m *AnyAnyMap) Remove(key any) (value any) {
m.mu.Lock() m.mu.Lock()
if m.data != nil { if m.data != nil {
var ok bool var ok bool
@ -333,7 +333,7 @@ func (m *AnyAnyMap) Remove(key interface{}) (value interface{}) {
} }
// Removes batch deletes values of the map by keys. // Removes batch deletes values of the map by keys.
func (m *AnyAnyMap) Removes(keys []interface{}) { func (m *AnyAnyMap) Removes(keys []any) {
m.mu.Lock() m.mu.Lock()
if m.data != nil { if m.data != nil {
for _, key := range keys { for _, key := range keys {
@ -344,11 +344,11 @@ func (m *AnyAnyMap) Removes(keys []interface{}) {
} }
// Keys returns all keys of the map as a slice. // Keys returns all keys of the map as a slice.
func (m *AnyAnyMap) Keys() []interface{} { func (m *AnyAnyMap) Keys() []any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
var ( var (
keys = make([]interface{}, len(m.data)) keys = make([]any, len(m.data))
index = 0 index = 0
) )
for key := range m.data { for key := range m.data {
@ -359,11 +359,11 @@ func (m *AnyAnyMap) Keys() []interface{} {
} }
// Values returns all values of the map as a slice. // Values returns all values of the map as a slice.
func (m *AnyAnyMap) Values() []interface{} { func (m *AnyAnyMap) Values() []any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
var ( var (
values = make([]interface{}, len(m.data)) values = make([]any, len(m.data))
index = 0 index = 0
) )
for _, value := range m.data { for _, value := range m.data {
@ -375,7 +375,7 @@ func (m *AnyAnyMap) Values() []interface{} {
// Contains checks whether a key exists. // Contains checks whether a key exists.
// It returns true if the `key` exists, or else false. // It returns true if the `key` exists, or else false.
func (m *AnyAnyMap) Contains(key interface{}) bool { func (m *AnyAnyMap) Contains(key any) bool {
var ok bool var ok bool
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
@ -402,26 +402,26 @@ func (m *AnyAnyMap) IsEmpty() bool {
// Clear deletes all data of the map, it will remake a new underlying data map. // Clear deletes all data of the map, it will remake a new underlying data map.
func (m *AnyAnyMap) Clear() { func (m *AnyAnyMap) Clear() {
m.mu.Lock() m.mu.Lock()
m.data = make(map[interface{}]interface{}) m.data = make(map[any]any)
m.mu.Unlock() m.mu.Unlock()
} }
// Replace the data of the map with given `data`. // Replace the data of the map with given `data`.
func (m *AnyAnyMap) Replace(data map[interface{}]interface{}) { func (m *AnyAnyMap) Replace(data map[any]any) {
m.mu.Lock() m.mu.Lock()
m.data = data m.data = data
m.mu.Unlock() m.mu.Unlock()
} }
// LockFunc locks writing with given callback function `f` within RWMutex.Lock. // LockFunc locks writing with given callback function `f` within RWMutex.Lock.
func (m *AnyAnyMap) LockFunc(f func(m map[interface{}]interface{})) { func (m *AnyAnyMap) LockFunc(f func(m map[any]any)) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
f(m.data) f(m.data)
} }
// RLockFunc locks reading with given callback function `f` within RWMutex.RLock. // RLockFunc locks reading with given callback function `f` within RWMutex.RLock.
func (m *AnyAnyMap) RLockFunc(f func(m map[interface{}]interface{})) { func (m *AnyAnyMap) RLockFunc(f func(m map[any]any)) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
f(m.data) f(m.data)
@ -431,7 +431,7 @@ func (m *AnyAnyMap) RLockFunc(f func(m map[interface{}]interface{})) {
func (m *AnyAnyMap) Flip() { func (m *AnyAnyMap) Flip() {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
n := make(map[interface{}]interface{}, len(m.data)) n := make(map[any]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
n[v] = k n[v] = k
} }
@ -475,9 +475,9 @@ func (m *AnyAnyMap) UnmarshalJSON(b []byte) error {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]interface{}) m.data = make(map[any]any)
} }
var data map[string]interface{} var data map[string]any
if err := json.UnmarshalUseNumber(b, &data); err != nil { if err := json.UnmarshalUseNumber(b, &data); err != nil {
return err return err
} }
@ -488,11 +488,11 @@ func (m *AnyAnyMap) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for map. // UnmarshalValue is an interface implement which sets any type of value for map.
func (m *AnyAnyMap) UnmarshalValue(value interface{}) (err error) { func (m *AnyAnyMap) UnmarshalValue(value any) (err error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]interface{}) m.data = make(map[any]any)
} }
for k, v := range gconv.Map(value) { for k, v := range gconv.Map(value) {
m.data[k] = v m.data[k] = v
@ -501,14 +501,14 @@ func (m *AnyAnyMap) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (m *AnyAnyMap) DeepCopy() interface{} { func (m *AnyAnyMap) DeepCopy() any {
if m == nil { if m == nil {
return nil return nil
} }
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[interface{}]interface{}, len(m.data)) data := make(map[any]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = deepcopy.Copy(v) data[k] = deepcopy.Copy(v)
} }
@ -540,7 +540,7 @@ func (m *AnyAnyMap) IsSubOf(other *AnyAnyMap) bool {
// The returned `addedKeys` are the keys that are in map `m` but not in map `other`. // The returned `addedKeys` are the keys that are in map `m` but not in map `other`.
// The returned `removedKeys` are the keys that are in map `other` but not in map `m`. // The returned `removedKeys` are the keys that are in map `other` but not in map `m`.
// The returned `updatedKeys` are the keys that are both in map `m` and `other` but their values and not equal (`!=`). // The returned `updatedKeys` are the keys that are both in map `m` and `other` but their values and not equal (`!=`).
func (m *AnyAnyMap) Diff(other *AnyAnyMap) (addedKeys, removedKeys, updatedKeys []interface{}) { func (m *AnyAnyMap) Diff(other *AnyAnyMap) (addedKeys, removedKeys, updatedKeys []any) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
other.mu.RLock() other.mu.RLock()

View File

@ -18,10 +18,10 @@ import (
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
) )
// IntAnyMap implements map[int]interface{} with RWMutex that has switch. // IntAnyMap implements map[int]any with RWMutex that has switch.
type IntAnyMap struct { type IntAnyMap struct {
mu rwmutex.RWMutex mu rwmutex.RWMutex
data map[int]interface{} data map[int]any
} }
// NewIntAnyMap returns an empty IntAnyMap object. // NewIntAnyMap returns an empty IntAnyMap object.
@ -30,14 +30,14 @@ type IntAnyMap struct {
func NewIntAnyMap(safe ...bool) *IntAnyMap { func NewIntAnyMap(safe ...bool) *IntAnyMap {
return &IntAnyMap{ return &IntAnyMap{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
data: make(map[int]interface{}), data: make(map[int]any),
} }
} }
// NewIntAnyMapFrom creates and returns a hash map from given map `data`. // NewIntAnyMapFrom creates and returns a hash map from given map `data`.
// Note that, the param `data` map will be set as the underlying data map(no deep copy), // Note that, the param `data` map will be set as the underlying data map(no deep copy),
// there might be some concurrent-safe issues when changing the map outside. // there might be some concurrent-safe issues when changing the map outside.
func NewIntAnyMapFrom(data map[int]interface{}, safe ...bool) *IntAnyMap { func NewIntAnyMapFrom(data map[int]any, safe ...bool) *IntAnyMap {
return &IntAnyMap{ return &IntAnyMap{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
data: data, data: data,
@ -46,7 +46,7 @@ func NewIntAnyMapFrom(data map[int]interface{}, safe ...bool) *IntAnyMap {
// Iterator iterates the hash map readonly with custom callback function `f`. // Iterator iterates the hash map readonly with custom callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (m *IntAnyMap) Iterator(f func(k int, v interface{}) bool) { func (m *IntAnyMap) Iterator(f func(k int, v any) bool) {
for k, v := range m.Map() { for k, v := range m.Map() {
if !f(k, v) { if !f(k, v) {
break break
@ -62,23 +62,23 @@ func (m *IntAnyMap) Clone() *IntAnyMap {
// Map returns the underlying data map. // Map returns the underlying data map.
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
// or else a pointer to the underlying data. // or else a pointer to the underlying data.
func (m *IntAnyMap) Map() map[int]interface{} { func (m *IntAnyMap) Map() map[int]any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
if !m.mu.IsSafe() { if !m.mu.IsSafe() {
return m.data return m.data
} }
data := make(map[int]interface{}, len(m.data)) data := make(map[int]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = v data[k] = v
} }
return data return data
} }
// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. // MapStrAny returns a copy of the underlying data of the map as map[string]any.
func (m *IntAnyMap) MapStrAny() map[string]interface{} { func (m *IntAnyMap) MapStrAny() map[string]any {
m.mu.RLock() m.mu.RLock()
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[gconv.String(k)] = v data[gconv.String(k)] = v
} }
@ -87,10 +87,10 @@ func (m *IntAnyMap) MapStrAny() map[string]interface{} {
} }
// MapCopy returns a copy of the underlying data of the hash map. // MapCopy returns a copy of the underlying data of the hash map.
func (m *IntAnyMap) MapCopy() map[int]interface{} { func (m *IntAnyMap) MapCopy() map[int]any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[int]interface{}, len(m.data)) data := make(map[int]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = v data[k] = v
} }
@ -121,17 +121,17 @@ func (m *IntAnyMap) FilterNil() {
} }
// Set sets key-value to the hash map. // Set sets key-value to the hash map.
func (m *IntAnyMap) Set(key int, val interface{}) { func (m *IntAnyMap) Set(key int, val any) {
m.mu.Lock() m.mu.Lock()
if m.data == nil { if m.data == nil {
m.data = make(map[int]interface{}) m.data = make(map[int]any)
} }
m.data[key] = val m.data[key] = val
m.mu.Unlock() m.mu.Unlock()
} }
// Sets batch sets key-values to the hash map. // Sets batch sets key-values to the hash map.
func (m *IntAnyMap) Sets(data map[int]interface{}) { func (m *IntAnyMap) Sets(data map[int]any) {
m.mu.Lock() m.mu.Lock()
if m.data == nil { if m.data == nil {
m.data = data m.data = data
@ -145,7 +145,7 @@ func (m *IntAnyMap) Sets(data map[int]interface{}) {
// Search searches the map with given `key`. // Search searches the map with given `key`.
// Second return parameter `found` is true if key was found, otherwise false. // Second return parameter `found` is true if key was found, otherwise false.
func (m *IntAnyMap) Search(key int) (value interface{}, found bool) { func (m *IntAnyMap) Search(key int) (value any, found bool) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
value, found = m.data[key] value, found = m.data[key]
@ -155,7 +155,7 @@ func (m *IntAnyMap) Search(key int) (value interface{}, found bool) {
} }
// Get returns the value by given `key`. // Get returns the value by given `key`.
func (m *IntAnyMap) Get(key int) (value interface{}) { func (m *IntAnyMap) Get(key int) (value any) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
value = m.data[key] value = m.data[key]
@ -165,7 +165,7 @@ func (m *IntAnyMap) Get(key int) (value interface{}) {
} }
// Pop retrieves and deletes an item from the map. // Pop retrieves and deletes an item from the map.
func (m *IntAnyMap) Pop() (key int, value interface{}) { func (m *IntAnyMap) Pop() (key int, value any) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
for key, value = range m.data { for key, value = range m.data {
@ -177,7 +177,7 @@ func (m *IntAnyMap) Pop() (key int, value interface{}) {
// Pops retrieves and deletes `size` items from the map. // Pops retrieves and deletes `size` items from the map.
// It returns all items if size == -1. // It returns all items if size == -1.
func (m *IntAnyMap) Pops(size int) map[int]interface{} { func (m *IntAnyMap) Pops(size int) map[int]any {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if size > len(m.data) || size == -1 { if size > len(m.data) || size == -1 {
@ -188,7 +188,7 @@ func (m *IntAnyMap) Pops(size int) map[int]interface{} {
} }
var ( var (
index = 0 index = 0
newMap = make(map[int]interface{}, size) newMap = make(map[int]any, size)
) )
for k, v := range m.data { for k, v := range m.data {
delete(m.data, k) delete(m.data, k)
@ -210,16 +210,16 @@ func (m *IntAnyMap) Pops(size int) map[int]interface{} {
// and its return value will be set to the map with `key`. // and its return value will be set to the map with `key`.
// //
// It returns value with given `key`. // It returns value with given `key`.
func (m *IntAnyMap) doSetWithLockCheck(key int, value interface{}) interface{} { func (m *IntAnyMap) doSetWithLockCheck(key int, value any) any {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[int]interface{}) m.data = make(map[int]any)
} }
if v, ok := m.data[key]; ok { if v, ok := m.data[key]; ok {
return v return v
} }
if f, ok := value.(func() interface{}); ok { if f, ok := value.(func() any); ok {
value = f() value = f()
} }
if value != nil { if value != nil {
@ -230,7 +230,7 @@ func (m *IntAnyMap) doSetWithLockCheck(key int, value interface{}) interface{} {
// GetOrSet returns the value by key, // GetOrSet returns the value by key,
// or sets value with given `value` if it does not exist and then returns this value. // or sets value with given `value` if it does not exist and then returns this value.
func (m *IntAnyMap) GetOrSet(key int, value interface{}) interface{} { func (m *IntAnyMap) GetOrSet(key int, value any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, value) return m.doSetWithLockCheck(key, value)
} else { } else {
@ -240,7 +240,7 @@ func (m *IntAnyMap) GetOrSet(key int, value interface{}) interface{} {
// GetOrSetFunc returns the value by key, // GetOrSetFunc returns the value by key,
// or sets value with returned value of callback function `f` if it does not exist and returns this value. // or sets value with returned value of callback function `f` if it does not exist and returns this value.
func (m *IntAnyMap) GetOrSetFunc(key int, f func() interface{}) interface{} { func (m *IntAnyMap) GetOrSetFunc(key int, f func() any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, f()) return m.doSetWithLockCheck(key, f())
} else { } else {
@ -253,7 +253,7 @@ func (m *IntAnyMap) GetOrSetFunc(key int, f func() interface{}) interface{} {
// //
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f`
// with mutex.Lock of the hash map. // with mutex.Lock of the hash map.
func (m *IntAnyMap) GetOrSetFuncLock(key int, f func() interface{}) interface{} { func (m *IntAnyMap) GetOrSetFuncLock(key int, f func() any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, f) return m.doSetWithLockCheck(key, f)
} else { } else {
@ -269,25 +269,25 @@ func (m *IntAnyMap) GetVar(key int) *gvar.Var {
// GetVarOrSet returns a Var with result from GetVarOrSet. // GetVarOrSet returns a Var with result from GetVarOrSet.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *IntAnyMap) GetVarOrSet(key int, value interface{}) *gvar.Var { func (m *IntAnyMap) GetVarOrSet(key int, value any) *gvar.Var {
return gvar.New(m.GetOrSet(key, value)) return gvar.New(m.GetOrSet(key, value))
} }
// GetVarOrSetFunc returns a Var with result from GetOrSetFunc. // GetVarOrSetFunc returns a Var with result from GetOrSetFunc.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *IntAnyMap) GetVarOrSetFunc(key int, f func() interface{}) *gvar.Var { func (m *IntAnyMap) GetVarOrSetFunc(key int, f func() any) *gvar.Var {
return gvar.New(m.GetOrSetFunc(key, f)) return gvar.New(m.GetOrSetFunc(key, f))
} }
// GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock. // GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *IntAnyMap) GetVarOrSetFuncLock(key int, f func() interface{}) *gvar.Var { func (m *IntAnyMap) GetVarOrSetFuncLock(key int, f func() any) *gvar.Var {
return gvar.New(m.GetOrSetFuncLock(key, f)) return gvar.New(m.GetOrSetFuncLock(key, f))
} }
// SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true.
// It returns false if `key` exists, and `value` would be ignored. // It returns false if `key` exists, and `value` would be ignored.
func (m *IntAnyMap) SetIfNotExist(key int, value interface{}) bool { func (m *IntAnyMap) SetIfNotExist(key int, value any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, value) m.doSetWithLockCheck(key, value)
return true return true
@ -297,7 +297,7 @@ func (m *IntAnyMap) SetIfNotExist(key int, value interface{}) bool {
// SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true.
// It returns false if `key` exists, and `value` would be ignored. // It returns false if `key` exists, and `value` would be ignored.
func (m *IntAnyMap) SetIfNotExistFunc(key int, f func() interface{}) bool { func (m *IntAnyMap) SetIfNotExistFunc(key int, f func() any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, f()) m.doSetWithLockCheck(key, f())
return true return true
@ -310,7 +310,7 @@ func (m *IntAnyMap) SetIfNotExistFunc(key int, f func() interface{}) bool {
// //
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
// it executes function `f` with mutex.Lock of the hash map. // it executes function `f` with mutex.Lock of the hash map.
func (m *IntAnyMap) SetIfNotExistFuncLock(key int, f func() interface{}) bool { func (m *IntAnyMap) SetIfNotExistFuncLock(key int, f func() any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, f) m.doSetWithLockCheck(key, f)
return true return true
@ -330,7 +330,7 @@ func (m *IntAnyMap) Removes(keys []int) {
} }
// Remove deletes value from map by given `key`, and return this deleted value. // Remove deletes value from map by given `key`, and return this deleted value.
func (m *IntAnyMap) Remove(key int) (value interface{}) { func (m *IntAnyMap) Remove(key int) (value any) {
m.mu.Lock() m.mu.Lock()
if m.data != nil { if m.data != nil {
var ok bool var ok bool
@ -358,10 +358,10 @@ func (m *IntAnyMap) Keys() []int {
} }
// Values returns all values of the map as a slice. // Values returns all values of the map as a slice.
func (m *IntAnyMap) Values() []interface{} { func (m *IntAnyMap) Values() []any {
m.mu.RLock() m.mu.RLock()
var ( var (
values = make([]interface{}, len(m.data)) values = make([]any, len(m.data))
index = 0 index = 0
) )
for _, value := range m.data { for _, value := range m.data {
@ -401,26 +401,26 @@ func (m *IntAnyMap) IsEmpty() bool {
// Clear deletes all data of the map, it will remake a new underlying data map. // Clear deletes all data of the map, it will remake a new underlying data map.
func (m *IntAnyMap) Clear() { func (m *IntAnyMap) Clear() {
m.mu.Lock() m.mu.Lock()
m.data = make(map[int]interface{}) m.data = make(map[int]any)
m.mu.Unlock() m.mu.Unlock()
} }
// Replace the data of the map with given `data`. // Replace the data of the map with given `data`.
func (m *IntAnyMap) Replace(data map[int]interface{}) { func (m *IntAnyMap) Replace(data map[int]any) {
m.mu.Lock() m.mu.Lock()
m.data = data m.data = data
m.mu.Unlock() m.mu.Unlock()
} }
// LockFunc locks writing with given callback function `f` within RWMutex.Lock. // LockFunc locks writing with given callback function `f` within RWMutex.Lock.
func (m *IntAnyMap) LockFunc(f func(m map[int]interface{})) { func (m *IntAnyMap) LockFunc(f func(m map[int]any)) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
f(m.data) f(m.data)
} }
// RLockFunc locks reading with given callback function `f` within RWMutex.RLock. // RLockFunc locks reading with given callback function `f` within RWMutex.RLock.
func (m *IntAnyMap) RLockFunc(f func(m map[int]interface{})) { func (m *IntAnyMap) RLockFunc(f func(m map[int]any)) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
f(m.data) f(m.data)
@ -430,7 +430,7 @@ func (m *IntAnyMap) RLockFunc(f func(m map[int]interface{})) {
func (m *IntAnyMap) Flip() { func (m *IntAnyMap) Flip() {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
n := make(map[int]interface{}, len(m.data)) n := make(map[int]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
n[gconv.Int(v)] = k n[gconv.Int(v)] = k
} }
@ -476,7 +476,7 @@ func (m *IntAnyMap) UnmarshalJSON(b []byte) error {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[int]interface{}) m.data = make(map[int]any)
} }
if err := json.UnmarshalUseNumber(b, &m.data); err != nil { if err := json.UnmarshalUseNumber(b, &m.data); err != nil {
return err return err
@ -485,11 +485,11 @@ func (m *IntAnyMap) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for map. // UnmarshalValue is an interface implement which sets any type of value for map.
func (m *IntAnyMap) UnmarshalValue(value interface{}) (err error) { func (m *IntAnyMap) UnmarshalValue(value any) (err error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[int]interface{}) m.data = make(map[int]any)
} }
switch value.(type) { switch value.(type) {
case string, []byte: case string, []byte:
@ -503,13 +503,13 @@ func (m *IntAnyMap) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (m *IntAnyMap) DeepCopy() interface{} { func (m *IntAnyMap) DeepCopy() any {
if m == nil { if m == nil {
return nil return nil
} }
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[int]interface{}, len(m.data)) data := make(map[int]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = deepcopy.Copy(v) data[k] = deepcopy.Copy(v)
} }

View File

@ -70,10 +70,10 @@ func (m *IntIntMap) Map() map[int]int {
return data return data
} }
// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. // MapStrAny returns a copy of the underlying data of the map as map[string]any.
func (m *IntIntMap) MapStrAny() map[string]interface{} { func (m *IntIntMap) MapStrAny() map[string]any {
m.mu.RLock() m.mu.RLock()
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[gconv.String(k)] = v data[gconv.String(k)] = v
} }
@ -453,7 +453,7 @@ func (m *IntIntMap) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for map. // UnmarshalValue is an interface implement which sets any type of value for map.
func (m *IntIntMap) UnmarshalValue(value interface{}) (err error) { func (m *IntIntMap) UnmarshalValue(value any) (err error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
@ -471,7 +471,7 @@ func (m *IntIntMap) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (m *IntIntMap) DeepCopy() interface{} { func (m *IntIntMap) DeepCopy() any {
if m == nil { if m == nil {
return nil return nil
} }

View File

@ -70,10 +70,10 @@ func (m *IntStrMap) Map() map[int]string {
return data return data
} }
// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. // MapStrAny returns a copy of the underlying data of the map as map[string]any.
func (m *IntStrMap) MapStrAny() map[string]interface{} { func (m *IntStrMap) MapStrAny() map[string]any {
m.mu.RLock() m.mu.RLock()
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[gconv.String(k)] = v data[gconv.String(k)] = v
} }
@ -453,7 +453,7 @@ func (m *IntStrMap) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for map. // UnmarshalValue is an interface implement which sets any type of value for map.
func (m *IntStrMap) UnmarshalValue(value interface{}) (err error) { func (m *IntStrMap) UnmarshalValue(value any) (err error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
@ -471,7 +471,7 @@ func (m *IntStrMap) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (m *IntStrMap) DeepCopy() interface{} { func (m *IntStrMap) DeepCopy() any {
if m == nil { if m == nil {
return nil return nil
} }

View File

@ -18,10 +18,10 @@ import (
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
) )
// StrAnyMap implements map[string]interface{} with RWMutex that has switch. // StrAnyMap implements map[string]any with RWMutex that has switch.
type StrAnyMap struct { type StrAnyMap struct {
mu rwmutex.RWMutex mu rwmutex.RWMutex
data map[string]interface{} data map[string]any
} }
// NewStrAnyMap returns an empty StrAnyMap object. // NewStrAnyMap returns an empty StrAnyMap object.
@ -30,14 +30,14 @@ type StrAnyMap struct {
func NewStrAnyMap(safe ...bool) *StrAnyMap { func NewStrAnyMap(safe ...bool) *StrAnyMap {
return &StrAnyMap{ return &StrAnyMap{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
data: make(map[string]interface{}), data: make(map[string]any),
} }
} }
// NewStrAnyMapFrom creates and returns a hash map from given map `data`. // NewStrAnyMapFrom creates and returns a hash map from given map `data`.
// Note that, the param `data` map will be set as the underlying data map(no deep copy), // Note that, the param `data` map will be set as the underlying data map(no deep copy),
// there might be some concurrent-safe issues when changing the map outside. // there might be some concurrent-safe issues when changing the map outside.
func NewStrAnyMapFrom(data map[string]interface{}, safe ...bool) *StrAnyMap { func NewStrAnyMapFrom(data map[string]any, safe ...bool) *StrAnyMap {
return &StrAnyMap{ return &StrAnyMap{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
data: data, data: data,
@ -46,7 +46,7 @@ func NewStrAnyMapFrom(data map[string]interface{}, safe ...bool) *StrAnyMap {
// Iterator iterates the hash map readonly with custom callback function `f`. // Iterator iterates the hash map readonly with custom callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (m *StrAnyMap) Iterator(f func(k string, v interface{}) bool) { func (m *StrAnyMap) Iterator(f func(k string, v any) bool) {
for k, v := range m.Map() { for k, v := range m.Map() {
if !f(k, v) { if !f(k, v) {
break break
@ -62,29 +62,29 @@ func (m *StrAnyMap) Clone() *StrAnyMap {
// Map returns the underlying data map. // Map returns the underlying data map.
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
// or else a pointer to the underlying data. // or else a pointer to the underlying data.
func (m *StrAnyMap) Map() map[string]interface{} { func (m *StrAnyMap) Map() map[string]any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
if !m.mu.IsSafe() { if !m.mu.IsSafe() {
return m.data return m.data
} }
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = v data[k] = v
} }
return data return data
} }
// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. // MapStrAny returns a copy of the underlying data of the map as map[string]any.
func (m *StrAnyMap) MapStrAny() map[string]interface{} { func (m *StrAnyMap) MapStrAny() map[string]any {
return m.Map() return m.Map()
} }
// MapCopy returns a copy of the underlying data of the hash map. // MapCopy returns a copy of the underlying data of the hash map.
func (m *StrAnyMap) MapCopy() map[string]interface{} { func (m *StrAnyMap) MapCopy() map[string]any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = v data[k] = v
} }
@ -115,17 +115,17 @@ func (m *StrAnyMap) FilterNil() {
} }
// Set sets key-value to the hash map. // Set sets key-value to the hash map.
func (m *StrAnyMap) Set(key string, val interface{}) { func (m *StrAnyMap) Set(key string, val any) {
m.mu.Lock() m.mu.Lock()
if m.data == nil { if m.data == nil {
m.data = make(map[string]interface{}) m.data = make(map[string]any)
} }
m.data[key] = val m.data[key] = val
m.mu.Unlock() m.mu.Unlock()
} }
// Sets batch sets key-values to the hash map. // Sets batch sets key-values to the hash map.
func (m *StrAnyMap) Sets(data map[string]interface{}) { func (m *StrAnyMap) Sets(data map[string]any) {
m.mu.Lock() m.mu.Lock()
if m.data == nil { if m.data == nil {
m.data = data m.data = data
@ -139,7 +139,7 @@ func (m *StrAnyMap) Sets(data map[string]interface{}) {
// Search searches the map with given `key`. // Search searches the map with given `key`.
// Second return parameter `found` is true if key was found, otherwise false. // Second return parameter `found` is true if key was found, otherwise false.
func (m *StrAnyMap) Search(key string) (value interface{}, found bool) { func (m *StrAnyMap) Search(key string) (value any, found bool) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
value, found = m.data[key] value, found = m.data[key]
@ -149,7 +149,7 @@ func (m *StrAnyMap) Search(key string) (value interface{}, found bool) {
} }
// Get returns the value by given `key`. // Get returns the value by given `key`.
func (m *StrAnyMap) Get(key string) (value interface{}) { func (m *StrAnyMap) Get(key string) (value any) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
value = m.data[key] value = m.data[key]
@ -159,7 +159,7 @@ func (m *StrAnyMap) Get(key string) (value interface{}) {
} }
// Pop retrieves and deletes an item from the map. // Pop retrieves and deletes an item from the map.
func (m *StrAnyMap) Pop() (key string, value interface{}) { func (m *StrAnyMap) Pop() (key string, value any) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
for key, value = range m.data { for key, value = range m.data {
@ -171,7 +171,7 @@ func (m *StrAnyMap) Pop() (key string, value interface{}) {
// Pops retrieves and deletes `size` items from the map. // Pops retrieves and deletes `size` items from the map.
// It returns all items if size == -1. // It returns all items if size == -1.
func (m *StrAnyMap) Pops(size int) map[string]interface{} { func (m *StrAnyMap) Pops(size int) map[string]any {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if size > len(m.data) || size == -1 { if size > len(m.data) || size == -1 {
@ -182,7 +182,7 @@ func (m *StrAnyMap) Pops(size int) map[string]interface{} {
} }
var ( var (
index = 0 index = 0
newMap = make(map[string]interface{}, size) newMap = make(map[string]any, size)
) )
for k, v := range m.data { for k, v := range m.data {
delete(m.data, k) delete(m.data, k)
@ -204,16 +204,16 @@ func (m *StrAnyMap) Pops(size int) map[string]interface{} {
// and its return value will be set to the map with `key`. // and its return value will be set to the map with `key`.
// //
// It returns value with given `key`. // It returns value with given `key`.
func (m *StrAnyMap) doSetWithLockCheck(key string, value interface{}) interface{} { func (m *StrAnyMap) doSetWithLockCheck(key string, value any) any {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[string]interface{}) m.data = make(map[string]any)
} }
if v, ok := m.data[key]; ok { if v, ok := m.data[key]; ok {
return v return v
} }
if f, ok := value.(func() interface{}); ok { if f, ok := value.(func() any); ok {
value = f() value = f()
} }
if value != nil { if value != nil {
@ -224,7 +224,7 @@ func (m *StrAnyMap) doSetWithLockCheck(key string, value interface{}) interface{
// GetOrSet returns the value by key, // GetOrSet returns the value by key,
// or sets value with given `value` if it does not exist and then returns this value. // or sets value with given `value` if it does not exist and then returns this value.
func (m *StrAnyMap) GetOrSet(key string, value interface{}) interface{} { func (m *StrAnyMap) GetOrSet(key string, value any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, value) return m.doSetWithLockCheck(key, value)
} else { } else {
@ -235,7 +235,7 @@ func (m *StrAnyMap) GetOrSet(key string, value interface{}) interface{} {
// GetOrSetFunc returns the value by key, // GetOrSetFunc returns the value by key,
// or sets value with returned value of callback function `f` if it does not exist // or sets value with returned value of callback function `f` if it does not exist
// and then returns this value. // and then returns this value.
func (m *StrAnyMap) GetOrSetFunc(key string, f func() interface{}) interface{} { func (m *StrAnyMap) GetOrSetFunc(key string, f func() any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, f()) return m.doSetWithLockCheck(key, f())
} else { } else {
@ -249,7 +249,7 @@ func (m *StrAnyMap) GetOrSetFunc(key string, f func() interface{}) interface{} {
// //
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f`
// with mutex.Lock of the hash map. // with mutex.Lock of the hash map.
func (m *StrAnyMap) GetOrSetFuncLock(key string, f func() interface{}) interface{} { func (m *StrAnyMap) GetOrSetFuncLock(key string, f func() any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, f) return m.doSetWithLockCheck(key, f)
} else { } else {
@ -265,25 +265,25 @@ func (m *StrAnyMap) GetVar(key string) *gvar.Var {
// GetVarOrSet returns a Var with result from GetVarOrSet. // GetVarOrSet returns a Var with result from GetVarOrSet.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *StrAnyMap) GetVarOrSet(key string, value interface{}) *gvar.Var { func (m *StrAnyMap) GetVarOrSet(key string, value any) *gvar.Var {
return gvar.New(m.GetOrSet(key, value)) return gvar.New(m.GetOrSet(key, value))
} }
// GetVarOrSetFunc returns a Var with result from GetOrSetFunc. // GetVarOrSetFunc returns a Var with result from GetOrSetFunc.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *StrAnyMap) GetVarOrSetFunc(key string, f func() interface{}) *gvar.Var { func (m *StrAnyMap) GetVarOrSetFunc(key string, f func() any) *gvar.Var {
return gvar.New(m.GetOrSetFunc(key, f)) return gvar.New(m.GetOrSetFunc(key, f))
} }
// GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock. // GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *StrAnyMap) GetVarOrSetFuncLock(key string, f func() interface{}) *gvar.Var { func (m *StrAnyMap) GetVarOrSetFuncLock(key string, f func() any) *gvar.Var {
return gvar.New(m.GetOrSetFuncLock(key, f)) return gvar.New(m.GetOrSetFuncLock(key, f))
} }
// SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true.
// It returns false if `key` exists, and `value` would be ignored. // It returns false if `key` exists, and `value` would be ignored.
func (m *StrAnyMap) SetIfNotExist(key string, value interface{}) bool { func (m *StrAnyMap) SetIfNotExist(key string, value any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, value) m.doSetWithLockCheck(key, value)
return true return true
@ -293,7 +293,7 @@ func (m *StrAnyMap) SetIfNotExist(key string, value interface{}) bool {
// SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true.
// It returns false if `key` exists, and `value` would be ignored. // It returns false if `key` exists, and `value` would be ignored.
func (m *StrAnyMap) SetIfNotExistFunc(key string, f func() interface{}) bool { func (m *StrAnyMap) SetIfNotExistFunc(key string, f func() any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, f()) m.doSetWithLockCheck(key, f())
return true return true
@ -306,7 +306,7 @@ func (m *StrAnyMap) SetIfNotExistFunc(key string, f func() interface{}) bool {
// //
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
// it executes function `f` with mutex.Lock of the hash map. // it executes function `f` with mutex.Lock of the hash map.
func (m *StrAnyMap) SetIfNotExistFuncLock(key string, f func() interface{}) bool { func (m *StrAnyMap) SetIfNotExistFuncLock(key string, f func() any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, f) m.doSetWithLockCheck(key, f)
return true return true
@ -326,7 +326,7 @@ func (m *StrAnyMap) Removes(keys []string) {
} }
// Remove deletes value from map by given `key`, and return this deleted value. // Remove deletes value from map by given `key`, and return this deleted value.
func (m *StrAnyMap) Remove(key string) (value interface{}) { func (m *StrAnyMap) Remove(key string) (value any) {
m.mu.Lock() m.mu.Lock()
if m.data != nil { if m.data != nil {
var ok bool var ok bool
@ -354,10 +354,10 @@ func (m *StrAnyMap) Keys() []string {
} }
// Values returns all values of the map as a slice. // Values returns all values of the map as a slice.
func (m *StrAnyMap) Values() []interface{} { func (m *StrAnyMap) Values() []any {
m.mu.RLock() m.mu.RLock()
var ( var (
values = make([]interface{}, len(m.data)) values = make([]any, len(m.data))
index = 0 index = 0
) )
for _, value := range m.data { for _, value := range m.data {
@ -397,26 +397,26 @@ func (m *StrAnyMap) IsEmpty() bool {
// Clear deletes all data of the map, it will remake a new underlying data map. // Clear deletes all data of the map, it will remake a new underlying data map.
func (m *StrAnyMap) Clear() { func (m *StrAnyMap) Clear() {
m.mu.Lock() m.mu.Lock()
m.data = make(map[string]interface{}) m.data = make(map[string]any)
m.mu.Unlock() m.mu.Unlock()
} }
// Replace the data of the map with given `data`. // Replace the data of the map with given `data`.
func (m *StrAnyMap) Replace(data map[string]interface{}) { func (m *StrAnyMap) Replace(data map[string]any) {
m.mu.Lock() m.mu.Lock()
m.data = data m.data = data
m.mu.Unlock() m.mu.Unlock()
} }
// LockFunc locks writing with given callback function `f` within RWMutex.Lock. // LockFunc locks writing with given callback function `f` within RWMutex.Lock.
func (m *StrAnyMap) LockFunc(f func(m map[string]interface{})) { func (m *StrAnyMap) LockFunc(f func(m map[string]any)) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
f(m.data) f(m.data)
} }
// RLockFunc locks reading with given callback function `f` within RWMutex.RLock. // RLockFunc locks reading with given callback function `f` within RWMutex.RLock.
func (m *StrAnyMap) RLockFunc(f func(m map[string]interface{})) { func (m *StrAnyMap) RLockFunc(f func(m map[string]any)) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
f(m.data) f(m.data)
@ -426,7 +426,7 @@ func (m *StrAnyMap) RLockFunc(f func(m map[string]interface{})) {
func (m *StrAnyMap) Flip() { func (m *StrAnyMap) Flip() {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
n := make(map[string]interface{}, len(m.data)) n := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
n[gconv.String(v)] = k n[gconv.String(v)] = k
} }
@ -472,7 +472,7 @@ func (m *StrAnyMap) UnmarshalJSON(b []byte) error {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[string]interface{}) m.data = make(map[string]any)
} }
if err := json.UnmarshalUseNumber(b, &m.data); err != nil { if err := json.UnmarshalUseNumber(b, &m.data); err != nil {
return err return err
@ -481,7 +481,7 @@ func (m *StrAnyMap) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for map. // UnmarshalValue is an interface implement which sets any type of value for map.
func (m *StrAnyMap) UnmarshalValue(value interface{}) (err error) { func (m *StrAnyMap) UnmarshalValue(value any) (err error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
m.data = gconv.Map(value) m.data = gconv.Map(value)
@ -489,13 +489,13 @@ func (m *StrAnyMap) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (m *StrAnyMap) DeepCopy() interface{} { func (m *StrAnyMap) DeepCopy() any {
if m == nil { if m == nil {
return nil return nil
} }
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = deepcopy.Copy(v) data[k] = deepcopy.Copy(v)
} }

View File

@ -71,11 +71,11 @@ func (m *StrIntMap) Map() map[string]int {
return data return data
} }
// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. // MapStrAny returns a copy of the underlying data of the map as map[string]any.
func (m *StrIntMap) MapStrAny() map[string]interface{} { func (m *StrIntMap) MapStrAny() map[string]any {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = v data[k] = v
} }
@ -457,7 +457,7 @@ func (m *StrIntMap) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for map. // UnmarshalValue is an interface implement which sets any type of value for map.
func (m *StrIntMap) UnmarshalValue(value interface{}) (err error) { func (m *StrIntMap) UnmarshalValue(value any) (err error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
@ -475,7 +475,7 @@ func (m *StrIntMap) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (m *StrIntMap) DeepCopy() interface{} { func (m *StrIntMap) DeepCopy() any {
if m == nil { if m == nil {
return nil return nil
} }

View File

@ -71,10 +71,10 @@ func (m *StrStrMap) Map() map[string]string {
return data return data
} }
// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. // MapStrAny returns a copy of the underlying data of the map as map[string]any.
func (m *StrStrMap) MapStrAny() map[string]interface{} { func (m *StrStrMap) MapStrAny() map[string]any {
m.mu.RLock() m.mu.RLock()
data := make(map[string]interface{}, len(m.data)) data := make(map[string]any, len(m.data))
for k, v := range m.data { for k, v := range m.data {
data[k] = v data[k] = v
} }
@ -456,7 +456,7 @@ func (m *StrStrMap) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for map. // UnmarshalValue is an interface implement which sets any type of value for map.
func (m *StrStrMap) UnmarshalValue(value interface{}) (err error) { func (m *StrStrMap) UnmarshalValue(value any) (err error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
m.data = gconv.MapStrStr(value) m.data = gconv.MapStrStr(value)
@ -464,7 +464,7 @@ func (m *StrStrMap) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (m *StrStrMap) DeepCopy() interface{} { func (m *StrStrMap) DeepCopy() any {
if m == nil { if m == nil {
return nil return nil
} }

View File

@ -28,13 +28,13 @@ import (
// Reference: http://en.wikipedia.org/wiki/Associative_array // Reference: http://en.wikipedia.org/wiki/Associative_array
type ListMap struct { type ListMap struct {
mu rwmutex.RWMutex mu rwmutex.RWMutex
data map[interface{}]*glist.Element data map[any]*glist.Element
list *glist.List list *glist.List
} }
type gListMapNode struct { type gListMapNode struct {
key interface{} key any
value interface{} value any
} }
// NewListMap returns an empty link map. // NewListMap returns an empty link map.
@ -44,7 +44,7 @@ type gListMapNode struct {
func NewListMap(safe ...bool) *ListMap { func NewListMap(safe ...bool) *ListMap {
return &ListMap{ return &ListMap{
mu: rwmutex.Create(safe...), mu: rwmutex.Create(safe...),
data: make(map[interface{}]*glist.Element), data: make(map[any]*glist.Element),
list: glist.New(), list: glist.New(),
} }
} }
@ -52,20 +52,20 @@ func NewListMap(safe ...bool) *ListMap {
// NewListMapFrom returns a link map from given map `data`. // NewListMapFrom returns a link map from given map `data`.
// Note that, the param `data` map will be set as the underlying data map(no deep copy), // Note that, the param `data` map will be set as the underlying data map(no deep copy),
// there might be some concurrent-safe issues when changing the map outside. // there might be some concurrent-safe issues when changing the map outside.
func NewListMapFrom(data map[interface{}]interface{}, safe ...bool) *ListMap { func NewListMapFrom(data map[any]any, safe ...bool) *ListMap {
m := NewListMap(safe...) m := NewListMap(safe...)
m.Sets(data) m.Sets(data)
return m return m
} }
// Iterator is alias of IteratorAsc. // Iterator is alias of IteratorAsc.
func (m *ListMap) Iterator(f func(key, value interface{}) bool) { func (m *ListMap) Iterator(f func(key, value any) bool) {
m.IteratorAsc(f) m.IteratorAsc(f)
} }
// IteratorAsc iterates the map readonly in ascending order with given callback function `f`. // IteratorAsc iterates the map readonly in ascending order with given callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (m *ListMap) IteratorAsc(f func(key interface{}, value interface{}) bool) { func (m *ListMap) IteratorAsc(f func(key any, value any) bool) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
if m.list != nil { if m.list != nil {
@ -79,7 +79,7 @@ func (m *ListMap) IteratorAsc(f func(key interface{}, value interface{}) bool) {
// IteratorDesc iterates the map readonly in descending order with given callback function `f`. // IteratorDesc iterates the map readonly in descending order with given callback function `f`.
// If `f` returns true, then it continues iterating; or false to stop. // If `f` returns true, then it continues iterating; or false to stop.
func (m *ListMap) IteratorDesc(f func(key interface{}, value interface{}) bool) { func (m *ListMap) IteratorDesc(f func(key any, value any) bool) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
if m.list != nil { if m.list != nil {
@ -99,15 +99,15 @@ func (m *ListMap) Clone(safe ...bool) *ListMap {
// Clear deletes all data of the map, it will remake a new underlying data map. // Clear deletes all data of the map, it will remake a new underlying data map.
func (m *ListMap) Clear() { func (m *ListMap) Clear() {
m.mu.Lock() m.mu.Lock()
m.data = make(map[interface{}]*glist.Element) m.data = make(map[any]*glist.Element)
m.list = glist.New() m.list = glist.New()
m.mu.Unlock() m.mu.Unlock()
} }
// Replace the data of the map with given `data`. // Replace the data of the map with given `data`.
func (m *ListMap) Replace(data map[interface{}]interface{}) { func (m *ListMap) Replace(data map[any]any) {
m.mu.Lock() m.mu.Lock()
m.data = make(map[interface{}]*glist.Element) m.data = make(map[any]*glist.Element)
m.list = glist.New() m.list = glist.New()
for key, value := range data { for key, value := range data {
if e, ok := m.data[key]; !ok { if e, ok := m.data[key]; !ok {
@ -120,12 +120,12 @@ func (m *ListMap) Replace(data map[interface{}]interface{}) {
} }
// Map returns a copy of the underlying data of the map. // Map returns a copy of the underlying data of the map.
func (m *ListMap) Map() map[interface{}]interface{} { func (m *ListMap) Map() map[any]any {
m.mu.RLock() m.mu.RLock()
var node *gListMapNode var node *gListMapNode
var data map[interface{}]interface{} var data map[any]any
if m.list != nil { if m.list != nil {
data = make(map[interface{}]interface{}, len(m.data)) data = make(map[any]any, len(m.data))
m.list.IteratorAsc(func(e *glist.Element) bool { m.list.IteratorAsc(func(e *glist.Element) bool {
node = e.Value.(*gListMapNode) node = e.Value.(*gListMapNode)
data[node.key] = node.value data[node.key] = node.value
@ -136,13 +136,13 @@ func (m *ListMap) Map() map[interface{}]interface{} {
return data return data
} }
// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. // MapStrAny returns a copy of the underlying data of the map as map[string]any.
func (m *ListMap) MapStrAny() map[string]interface{} { func (m *ListMap) MapStrAny() map[string]any {
m.mu.RLock() m.mu.RLock()
var node *gListMapNode var node *gListMapNode
var data map[string]interface{} var data map[string]any
if m.list != nil { if m.list != nil {
data = make(map[string]interface{}, len(m.data)) data = make(map[string]any, len(m.data))
m.list.IteratorAsc(func(e *glist.Element) bool { m.list.IteratorAsc(func(e *glist.Element) bool {
node = e.Value.(*gListMapNode) node = e.Value.(*gListMapNode)
data[gconv.String(node.key)] = node.value data[gconv.String(node.key)] = node.value
@ -158,7 +158,7 @@ func (m *ListMap) FilterEmpty() {
m.mu.Lock() m.mu.Lock()
if m.list != nil { if m.list != nil {
var ( var (
keys = make([]interface{}, 0) keys = make([]any, 0)
node *gListMapNode node *gListMapNode
) )
m.list.IteratorAsc(func(e *glist.Element) bool { m.list.IteratorAsc(func(e *glist.Element) bool {
@ -181,10 +181,10 @@ func (m *ListMap) FilterEmpty() {
} }
// Set sets key-value to the map. // Set sets key-value to the map.
func (m *ListMap) Set(key interface{}, value interface{}) { func (m *ListMap) Set(key any, value any) {
m.mu.Lock() m.mu.Lock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]*glist.Element) m.data = make(map[any]*glist.Element)
m.list = glist.New() m.list = glist.New()
} }
if e, ok := m.data[key]; !ok { if e, ok := m.data[key]; !ok {
@ -196,10 +196,10 @@ func (m *ListMap) Set(key interface{}, value interface{}) {
} }
// Sets batch sets key-values to the map. // Sets batch sets key-values to the map.
func (m *ListMap) Sets(data map[interface{}]interface{}) { func (m *ListMap) Sets(data map[any]any) {
m.mu.Lock() m.mu.Lock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]*glist.Element) m.data = make(map[any]*glist.Element)
m.list = glist.New() m.list = glist.New()
} }
for key, value := range data { for key, value := range data {
@ -214,7 +214,7 @@ func (m *ListMap) Sets(data map[interface{}]interface{}) {
// Search searches the map with given `key`. // Search searches the map with given `key`.
// Second return parameter `found` is true if key was found, otherwise false. // Second return parameter `found` is true if key was found, otherwise false.
func (m *ListMap) Search(key interface{}) (value interface{}, found bool) { func (m *ListMap) Search(key any) (value any, found bool) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
if e, ok := m.data[key]; ok { if e, ok := m.data[key]; ok {
@ -227,7 +227,7 @@ func (m *ListMap) Search(key interface{}) (value interface{}, found bool) {
} }
// Get returns the value by given `key`. // Get returns the value by given `key`.
func (m *ListMap) Get(key interface{}) (value interface{}) { func (m *ListMap) Get(key any) (value any) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
if e, ok := m.data[key]; ok { if e, ok := m.data[key]; ok {
@ -239,7 +239,7 @@ func (m *ListMap) Get(key interface{}) (value interface{}) {
} }
// Pop retrieves and deletes an item from the map. // Pop retrieves and deletes an item from the map.
func (m *ListMap) Pop() (key, value interface{}) { func (m *ListMap) Pop() (key, value any) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
for k, e := range m.data { for k, e := range m.data {
@ -253,7 +253,7 @@ func (m *ListMap) Pop() (key, value interface{}) {
// Pops retrieves and deletes `size` items from the map. // Pops retrieves and deletes `size` items from the map.
// It returns all items if size == -1. // It returns all items if size == -1.
func (m *ListMap) Pops(size int) map[interface{}]interface{} { func (m *ListMap) Pops(size int) map[any]any {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if size > len(m.data) || size == -1 { if size > len(m.data) || size == -1 {
@ -263,7 +263,7 @@ func (m *ListMap) Pops(size int) map[interface{}]interface{} {
return nil return nil
} }
index := 0 index := 0
newMap := make(map[interface{}]interface{}, size) newMap := make(map[any]any, size)
for k, e := range m.data { for k, e := range m.data {
value := e.Value.(*gListMapNode).value value := e.Value.(*gListMapNode).value
delete(m.data, k) delete(m.data, k)
@ -286,17 +286,17 @@ func (m *ListMap) Pops(size int) map[interface{}]interface{} {
// and its return value will be set to the map with `key`. // and its return value will be set to the map with `key`.
// //
// It returns value with given `key`. // It returns value with given `key`.
func (m *ListMap) doSetWithLockCheck(key interface{}, value interface{}) interface{} { func (m *ListMap) doSetWithLockCheck(key any, value any) any {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]*glist.Element) m.data = make(map[any]*glist.Element)
m.list = glist.New() m.list = glist.New()
} }
if e, ok := m.data[key]; ok { if e, ok := m.data[key]; ok {
return e.Value.(*gListMapNode).value return e.Value.(*gListMapNode).value
} }
if f, ok := value.(func() interface{}); ok { if f, ok := value.(func() any); ok {
value = f() value = f()
} }
if value != nil { if value != nil {
@ -307,7 +307,7 @@ func (m *ListMap) doSetWithLockCheck(key interface{}, value interface{}) interfa
// GetOrSet returns the value by key, // GetOrSet returns the value by key,
// or sets value with given `value` if it does not exist and then returns this value. // or sets value with given `value` if it does not exist and then returns this value.
func (m *ListMap) GetOrSet(key interface{}, value interface{}) interface{} { func (m *ListMap) GetOrSet(key any, value any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, value) return m.doSetWithLockCheck(key, value)
} else { } else {
@ -318,7 +318,7 @@ func (m *ListMap) GetOrSet(key interface{}, value interface{}) interface{} {
// GetOrSetFunc returns the value by key, // GetOrSetFunc returns the value by key,
// or sets value with returned value of callback function `f` if it does not exist // or sets value with returned value of callback function `f` if it does not exist
// and then returns this value. // and then returns this value.
func (m *ListMap) GetOrSetFunc(key interface{}, f func() interface{}) interface{} { func (m *ListMap) GetOrSetFunc(key any, f func() any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, f()) return m.doSetWithLockCheck(key, f())
} else { } else {
@ -332,7 +332,7 @@ func (m *ListMap) GetOrSetFunc(key interface{}, f func() interface{}) interface{
// //
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f`
// with mutex.Lock of the map. // with mutex.Lock of the map.
func (m *ListMap) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} { func (m *ListMap) GetOrSetFuncLock(key any, f func() any) any {
if v, ok := m.Search(key); !ok { if v, ok := m.Search(key); !ok {
return m.doSetWithLockCheck(key, f) return m.doSetWithLockCheck(key, f)
} else { } else {
@ -342,31 +342,31 @@ func (m *ListMap) GetOrSetFuncLock(key interface{}, f func() interface{}) interf
// GetVar returns a Var with the value by given `key`. // GetVar returns a Var with the value by given `key`.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *ListMap) GetVar(key interface{}) *gvar.Var { func (m *ListMap) GetVar(key any) *gvar.Var {
return gvar.New(m.Get(key)) return gvar.New(m.Get(key))
} }
// GetVarOrSet returns a Var with result from GetVarOrSet. // GetVarOrSet returns a Var with result from GetVarOrSet.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *ListMap) GetVarOrSet(key interface{}, value interface{}) *gvar.Var { func (m *ListMap) GetVarOrSet(key any, value any) *gvar.Var {
return gvar.New(m.GetOrSet(key, value)) return gvar.New(m.GetOrSet(key, value))
} }
// GetVarOrSetFunc returns a Var with result from GetOrSetFunc. // GetVarOrSetFunc returns a Var with result from GetOrSetFunc.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *ListMap) GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var { func (m *ListMap) GetVarOrSetFunc(key any, f func() any) *gvar.Var {
return gvar.New(m.GetOrSetFunc(key, f)) return gvar.New(m.GetOrSetFunc(key, f))
} }
// GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock. // GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock.
// The returned Var is un-concurrent safe. // The returned Var is un-concurrent safe.
func (m *ListMap) GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var { func (m *ListMap) GetVarOrSetFuncLock(key any, f func() any) *gvar.Var {
return gvar.New(m.GetOrSetFuncLock(key, f)) return gvar.New(m.GetOrSetFuncLock(key, f))
} }
// SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true.
// It returns false if `key` exists, and `value` would be ignored. // It returns false if `key` exists, and `value` would be ignored.
func (m *ListMap) SetIfNotExist(key interface{}, value interface{}) bool { func (m *ListMap) SetIfNotExist(key any, value any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, value) m.doSetWithLockCheck(key, value)
return true return true
@ -376,7 +376,7 @@ func (m *ListMap) SetIfNotExist(key interface{}, value interface{}) bool {
// SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true.
// It returns false if `key` exists, and `value` would be ignored. // It returns false if `key` exists, and `value` would be ignored.
func (m *ListMap) SetIfNotExistFunc(key interface{}, f func() interface{}) bool { func (m *ListMap) SetIfNotExistFunc(key any, f func() any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, f()) m.doSetWithLockCheck(key, f())
return true return true
@ -389,7 +389,7 @@ func (m *ListMap) SetIfNotExistFunc(key interface{}, f func() interface{}) bool
// //
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
// it executes function `f` with mutex.Lock of the map. // it executes function `f` with mutex.Lock of the map.
func (m *ListMap) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool { func (m *ListMap) SetIfNotExistFuncLock(key any, f func() any) bool {
if !m.Contains(key) { if !m.Contains(key) {
m.doSetWithLockCheck(key, f) m.doSetWithLockCheck(key, f)
return true return true
@ -398,7 +398,7 @@ func (m *ListMap) SetIfNotExistFuncLock(key interface{}, f func() interface{}) b
} }
// Remove deletes value from map by given `key`, and return this deleted value. // Remove deletes value from map by given `key`, and return this deleted value.
func (m *ListMap) Remove(key interface{}) (value interface{}) { func (m *ListMap) Remove(key any) (value any) {
m.mu.Lock() m.mu.Lock()
if m.data != nil { if m.data != nil {
if e, ok := m.data[key]; ok { if e, ok := m.data[key]; ok {
@ -412,7 +412,7 @@ func (m *ListMap) Remove(key interface{}) (value interface{}) {
} }
// Removes batch deletes values of the map by keys. // Removes batch deletes values of the map by keys.
func (m *ListMap) Removes(keys []interface{}) { func (m *ListMap) Removes(keys []any) {
m.mu.Lock() m.mu.Lock()
if m.data != nil { if m.data != nil {
for _, key := range keys { for _, key := range keys {
@ -426,10 +426,10 @@ func (m *ListMap) Removes(keys []interface{}) {
} }
// Keys returns all keys of the map as a slice in ascending order. // Keys returns all keys of the map as a slice in ascending order.
func (m *ListMap) Keys() []interface{} { func (m *ListMap) Keys() []any {
m.mu.RLock() m.mu.RLock()
var ( var (
keys = make([]interface{}, m.list.Len()) keys = make([]any, m.list.Len())
index = 0 index = 0
) )
if m.list != nil { if m.list != nil {
@ -444,10 +444,10 @@ func (m *ListMap) Keys() []interface{} {
} }
// Values returns all values of the map as a slice. // Values returns all values of the map as a slice.
func (m *ListMap) Values() []interface{} { func (m *ListMap) Values() []any {
m.mu.RLock() m.mu.RLock()
var ( var (
values = make([]interface{}, m.list.Len()) values = make([]any, m.list.Len())
index = 0 index = 0
) )
if m.list != nil { if m.list != nil {
@ -463,7 +463,7 @@ func (m *ListMap) Values() []interface{} {
// Contains checks whether a key exists. // Contains checks whether a key exists.
// It returns true if the `key` exists, or else false. // It returns true if the `key` exists, or else false.
func (m *ListMap) Contains(key interface{}) (ok bool) { func (m *ListMap) Contains(key any) (ok bool) {
m.mu.RLock() m.mu.RLock()
if m.data != nil { if m.data != nil {
_, ok = m.data[key] _, ok = m.data[key]
@ -501,7 +501,7 @@ func (m *ListMap) Merge(other *ListMap) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]*glist.Element) m.data = make(map[any]*glist.Element)
m.list = glist.New() m.list = glist.New()
} }
if other != m { if other != m {
@ -536,16 +536,16 @@ func (m ListMap) MarshalJSON() (jsonBytes []byte, err error) {
} }
buffer := bytes.NewBuffer(nil) buffer := bytes.NewBuffer(nil)
buffer.WriteByte('{') buffer.WriteByte('{')
m.Iterator(func(key, value interface{}) bool { m.Iterator(func(key, value any) bool {
valueBytes, valueJsonErr := json.Marshal(value) valueBytes, valueJSONErr := json.Marshal(value)
if valueJsonErr != nil { if valueJSONErr != nil {
err = valueJsonErr err = valueJSONErr
return false return false
} }
if buffer.Len() > 1 { if buffer.Len() > 1 {
buffer.WriteByte(',') buffer.WriteByte(',')
} }
buffer.WriteString(fmt.Sprintf(`"%v":%s`, key, valueBytes)) fmt.Fprintf(buffer, `"%v":%s`, key, valueBytes)
return true return true
}) })
buffer.WriteByte('}') buffer.WriteByte('}')
@ -557,10 +557,10 @@ func (m *ListMap) UnmarshalJSON(b []byte) error {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]*glist.Element) m.data = make(map[any]*glist.Element)
m.list = glist.New() m.list = glist.New()
} }
var data map[string]interface{} var data map[string]any
if err := json.UnmarshalUseNumber(b, &data); err != nil { if err := json.UnmarshalUseNumber(b, &data); err != nil {
return err return err
} }
@ -575,11 +575,11 @@ func (m *ListMap) UnmarshalJSON(b []byte) error {
} }
// UnmarshalValue is an interface implement which sets any type of value for map. // UnmarshalValue is an interface implement which sets any type of value for map.
func (m *ListMap) UnmarshalValue(value interface{}) (err error) { func (m *ListMap) UnmarshalValue(value any) (err error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.data == nil { if m.data == nil {
m.data = make(map[interface{}]*glist.Element) m.data = make(map[any]*glist.Element)
m.list = glist.New() m.list = glist.New()
} }
for k, v := range gconv.Map(value) { for k, v := range gconv.Map(value) {
@ -593,13 +593,13 @@ func (m *ListMap) UnmarshalValue(value interface{}) (err error) {
} }
// DeepCopy implements interface for deep copy of current type. // DeepCopy implements interface for deep copy of current type.
func (m *ListMap) DeepCopy() interface{} { func (m *ListMap) DeepCopy() any {
if m == nil { if m == nil {
return nil return nil
} }
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
data := make(map[interface{}]interface{}, len(m.data)) data := make(map[any]any, len(m.data))
if m.list != nil { if m.list != nil {
var node *gListMapNode var node *gListMapNode
m.list.IteratorAsc(func(e *glist.Element) bool { m.list.IteratorAsc(func(e *glist.Element) bool {

View File

@ -16,7 +16,7 @@ type TreeMap = gtree.RedBlackTree
// NewTreeMap instantiates a tree map with the custom comparator. // NewTreeMap instantiates a tree map with the custom comparator.
// The parameter `safe` is used to specify whether using tree in concurrent-safety, // The parameter `safe` is used to specify whether using tree in concurrent-safety,
// which is false in default. // which is false in default.
func NewTreeMap(comparator func(v1, v2 interface{}) int, safe ...bool) *TreeMap { func NewTreeMap(comparator func(v1, v2 any) int, safe ...bool) *TreeMap {
return gtree.NewRedBlackTree(comparator, safe...) return gtree.NewRedBlackTree(comparator, safe...)
} }
@ -25,6 +25,6 @@ func NewTreeMap(comparator func(v1, v2 interface{}) int, safe ...bool) *TreeMap
// there might be some concurrent-safe issues when changing the map outside. // there might be some concurrent-safe issues when changing the map outside.
// The parameter `safe` is used to specify whether using tree in concurrent-safety, // The parameter `safe` is used to specify whether using tree in concurrent-safety,
// which is false in default. // which is false in default.
func NewTreeMapFrom(comparator func(v1, v2 interface{}) int, data map[interface{}]interface{}, safe ...bool) *TreeMap { func NewTreeMapFrom(comparator func(v1, v2 any) int, data map[any]any, safe ...bool) *TreeMap {
return gtree.NewRedBlackTreeFrom(comparator, data, safe...) return gtree.NewRedBlackTreeFrom(comparator, data, safe...)
} }

View File

@ -14,7 +14,7 @@ import (
"github.com/gogf/gf/v2/util/gutil" "github.com/gogf/gf/v2/util/gutil"
) )
func getValue() interface{} { func getValue() any {
return 3 return 3
} }
@ -71,7 +71,7 @@ func Test_Map_Basic(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.New() m := gmap.New()
m.Set("key1", "val1") m.Set("key1", "val1")
t.Assert(m.Keys(), []interface{}{"key1"}) t.Assert(m.Keys(), []any{"key1"})
t.Assert(m.Get("key1"), "val1") t.Assert(m.Get("key1"), "val1")
t.Assert(m.Size(), 1) t.Assert(m.Size(), 1)
@ -91,14 +91,14 @@ func Test_Map_Basic(t *testing.T) {
t.AssertIN("val1", m.Values()) t.AssertIN("val1", m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
t.Assert(m.IsEmpty(), true) t.Assert(m.IsEmpty(), true)
m2 := gmap.NewFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) m2 := gmap.NewFrom(map[any]any{1: 1, "key1": "val1"})
t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"})
}) })
} }
@ -118,30 +118,30 @@ func Test_Map_Set_Fun(t *testing.T) {
func Test_Map_Batch(t *testing.T) { func Test_Map_Batch(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.New() m := gmap.New()
m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"})
t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"})
m.Removes([]interface{}{"key1", 1}) m.Removes([]any{"key1", 1})
t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"})
}) })
} }
func Test_Map_Iterator(t *testing.T) { func Test_Map_Iterator(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[interface{}]interface{}{1: 1, "key1": "val1"} expect := map[any]any{1: 1, "key1": "val1"}
m := gmap.NewFrom(expect) m := gmap.NewFrom(expect)
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
t.Assert(expect[k], v) t.Assert(expect[k], v)
return true return true
}) })
// 断言返回值对遍历控制 // 断言返回值对遍历控制
i := 0 i := 0
j := 0 j := 0
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
i++ i++
return true return true
}) })
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
j++ j++
return false return false
}) })
@ -152,12 +152,12 @@ func Test_Map_Iterator(t *testing.T) {
func Test_Map_Lock(t *testing.T) { func Test_Map_Lock(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[interface{}]interface{}{1: 1, "key1": "val1"} expect := map[any]any{1: 1, "key1": "val1"}
m := gmap.NewFrom(expect) m := gmap.NewFrom(expect)
m.LockFunc(func(m map[interface{}]interface{}) { m.LockFunc(func(m map[any]any) {
t.Assert(m, expect) t.Assert(m, expect)
}) })
m.RLockFunc(func(m map[interface{}]interface{}) { m.RLockFunc(func(m map[any]any) {
t.Assert(m, expect) t.Assert(m, expect)
}) })
}) })
@ -166,7 +166,7 @@ func Test_Map_Lock(t *testing.T) {
func Test_Map_Clone(t *testing.T) { func Test_Map_Clone(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
// clone 方法是深克隆 // clone 方法是深克隆
m := gmap.NewFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) m := gmap.NewFrom(map[any]any{1: 1, "key1": "val1"})
m_clone := m.Clone() m_clone := m.Clone()
m.Remove(1) m.Remove(1)
// 修改原 map,clone 后的 map 不影响 // 修改原 map,clone 后的 map 不影响
@ -185,6 +185,6 @@ func Test_Map_Basic_Merge(t *testing.T) {
m1.Set("key1", "val1") m1.Set("key1", "val1")
m2.Set("key2", "val2") m2.Set("key2", "val2")
m1.Merge(m2) m1.Merge(m2)
t.Assert(m1.Map(), map[interface{}]interface{}{"key1": "val1", "key2": "val2"}) t.Assert(m1.Map(), map[any]any{"key1": "val1", "key2": "val2"})
}) })
} }

View File

@ -22,7 +22,7 @@ func ExampleAnyAnyMap_Iterator() {
} }
var totalKey, totalValue int var totalKey, totalValue int
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
totalKey += k.(int) totalKey += k.(int)
totalValue += v.(int) totalValue += v.(int)
@ -149,7 +149,7 @@ func ExampleAnyAnyMap_Set() {
func ExampleAnyAnyMap_Sets() { func ExampleAnyAnyMap_Sets() {
m := gmap.New() m := gmap.New()
addMap := make(map[interface{}]interface{}) addMap := make(map[any]any)
addMap["key1"] = "val1" addMap["key1"] = "val1"
addMap["key2"] = "val2" addMap["key2"] = "val2"
addMap["key3"] = "val3" addMap["key3"] = "val3"
@ -252,10 +252,10 @@ func ExampleAnyAnyMap_GetOrSetFunc() {
m := gmap.New() m := gmap.New()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetOrSetFunc("key1", func() interface{} { fmt.Println(m.GetOrSetFunc("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetOrSetFunc("key2", func() interface{} { fmt.Println(m.GetOrSetFunc("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -268,10 +268,10 @@ func ExampleAnyAnyMap_GetOrSetFuncLock() {
m := gmap.New() m := gmap.New()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { fmt.Println(m.GetOrSetFuncLock("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { fmt.Println(m.GetOrSetFuncLock("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -308,10 +308,10 @@ func ExampleAnyAnyMap_GetVarOrSetFunc() {
m := gmap.New() m := gmap.New()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { fmt.Println(m.GetVarOrSetFunc("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { fmt.Println(m.GetVarOrSetFunc("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -324,10 +324,10 @@ func ExampleAnyAnyMap_GetVarOrSetFuncLock() {
m := gmap.New() m := gmap.New()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { fmt.Println(m.GetVarOrSetFuncLock("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { fmt.Println(m.GetVarOrSetFuncLock("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -350,10 +350,10 @@ func ExampleAnyAnyMap_SetIfNotExist() {
func ExampleAnyAnyMap_SetIfNotExistFunc() { func ExampleAnyAnyMap_SetIfNotExistFunc() {
var m gmap.Map var m gmap.Map
fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { fmt.Println(m.SetIfNotExistFunc("k1", func() any {
return "v1" return "v1"
})) }))
fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { fmt.Println(m.SetIfNotExistFunc("k1", func() any {
return "v2" return "v2"
})) }))
fmt.Println(m.Map()) fmt.Println(m.Map())
@ -366,10 +366,10 @@ func ExampleAnyAnyMap_SetIfNotExistFunc() {
func ExampleAnyAnyMap_SetIfNotExistFuncLock() { func ExampleAnyAnyMap_SetIfNotExistFuncLock() {
var m gmap.Map var m gmap.Map
fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { fmt.Println(m.SetIfNotExistFuncLock("k1", func() any {
return "v1" return "v1"
})) }))
fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { fmt.Println(m.SetIfNotExistFuncLock("k1", func() any {
return "v2" return "v2"
})) }))
fmt.Println(m.Map()) fmt.Println(m.Map())
@ -403,7 +403,7 @@ func ExampleAnyAnyMap_Removes() {
"k4": "v4", "k4": "v4",
}) })
removeList := make([]interface{}, 2) removeList := make([]any, 2)
removeList = append(removeList, "k1") removeList = append(removeList, "k1")
removeList = append(removeList, "k2") removeList = append(removeList, "k2")
@ -538,7 +538,7 @@ func ExampleAnyAnyMap_LockFunc() {
"k4": 4, "k4": 4,
}) })
m.LockFunc(func(m map[interface{}]interface{}) { m.LockFunc(func(m map[any]any) {
totalValue := 0 totalValue := 0
for _, v := range m { for _, v := range m {
totalValue += v.(int) totalValue += v.(int)
@ -559,7 +559,7 @@ func ExampleAnyAnyMap_RLockFunc() {
"k4": 4, "k4": 4,
}) })
m.RLockFunc(func(m map[interface{}]interface{}) { m.RLockFunc(func(m map[any]any) {
totalValue := 0 totalValue := 0
for _, v := range m { for _, v := range m {
totalValue += v.(int) totalValue += v.(int)

View File

@ -22,7 +22,7 @@ func ExampleIntAnyMap_Iterator() {
} }
var totalKey, totalValue int var totalKey, totalValue int
m.Iterator(func(k int, v interface{}) bool { m.Iterator(func(k int, v any) bool {
totalKey += k totalKey += k
totalValue += v.(int) totalValue += v.(int)
@ -149,7 +149,7 @@ func ExampleIntAnyMap_Set() {
func ExampleIntAnyMap_Sets() { func ExampleIntAnyMap_Sets() {
m := gmap.NewIntAnyMap() m := gmap.NewIntAnyMap()
addMap := make(map[int]interface{}) addMap := make(map[int]any)
addMap[1] = "val1" addMap[1] = "val1"
addMap[2] = "val2" addMap[2] = "val2"
addMap[3] = "val3" addMap[3] = "val3"
@ -252,10 +252,10 @@ func ExampleIntAnyMap_GetOrSetFunc() {
m := gmap.NewIntAnyMap() m := gmap.NewIntAnyMap()
m.Set(1, "val1") m.Set(1, "val1")
fmt.Println(m.GetOrSetFunc(1, func() interface{} { fmt.Println(m.GetOrSetFunc(1, func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetOrSetFunc(2, func() interface{} { fmt.Println(m.GetOrSetFunc(2, func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -268,10 +268,10 @@ func ExampleIntAnyMap_GetOrSetFuncLock() {
m := gmap.NewIntAnyMap() m := gmap.NewIntAnyMap()
m.Set(1, "val1") m.Set(1, "val1")
fmt.Println(m.GetOrSetFuncLock(1, func() interface{} { fmt.Println(m.GetOrSetFuncLock(1, func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetOrSetFuncLock(2, func() interface{} { fmt.Println(m.GetOrSetFuncLock(2, func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -308,10 +308,10 @@ func ExampleIntAnyMap_GetVarOrSetFunc() {
m := gmap.NewIntAnyMap() m := gmap.NewIntAnyMap()
m.Set(1, "val1") m.Set(1, "val1")
fmt.Println(m.GetVarOrSetFunc(1, func() interface{} { fmt.Println(m.GetVarOrSetFunc(1, func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetVarOrSetFunc(2, func() interface{} { fmt.Println(m.GetVarOrSetFunc(2, func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -324,10 +324,10 @@ func ExampleIntAnyMap_GetVarOrSetFuncLock() {
m := gmap.NewIntAnyMap() m := gmap.NewIntAnyMap()
m.Set(1, "val1") m.Set(1, "val1")
fmt.Println(m.GetVarOrSetFuncLock(1, func() interface{} { fmt.Println(m.GetVarOrSetFuncLock(1, func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetVarOrSetFuncLock(2, func() interface{} { fmt.Println(m.GetVarOrSetFuncLock(2, func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -350,10 +350,10 @@ func ExampleIntAnyMap_SetIfNotExist() {
func ExampleIntAnyMap_SetIfNotExistFunc() { func ExampleIntAnyMap_SetIfNotExistFunc() {
var m gmap.IntAnyMap var m gmap.IntAnyMap
fmt.Println(m.SetIfNotExistFunc(1, func() interface{} { fmt.Println(m.SetIfNotExistFunc(1, func() any {
return "v1" return "v1"
})) }))
fmt.Println(m.SetIfNotExistFunc(1, func() interface{} { fmt.Println(m.SetIfNotExistFunc(1, func() any {
return "v2" return "v2"
})) }))
fmt.Println(m.Map()) fmt.Println(m.Map())
@ -366,10 +366,10 @@ func ExampleIntAnyMap_SetIfNotExistFunc() {
func ExampleIntAnyMap_SetIfNotExistFuncLock() { func ExampleIntAnyMap_SetIfNotExistFuncLock() {
var m gmap.IntAnyMap var m gmap.IntAnyMap
fmt.Println(m.SetIfNotExistFuncLock(1, func() interface{} { fmt.Println(m.SetIfNotExistFuncLock(1, func() any {
return "v1" return "v1"
})) }))
fmt.Println(m.SetIfNotExistFuncLock(1, func() interface{} { fmt.Println(m.SetIfNotExistFuncLock(1, func() any {
return "v2" return "v2"
})) }))
fmt.Println(m.Map()) fmt.Println(m.Map())
@ -538,7 +538,7 @@ func ExampleIntAnyMap_LockFunc() {
4: 4, 4: 4,
}) })
m.LockFunc(func(m map[int]interface{}) { m.LockFunc(func(m map[int]any) {
totalValue := 0 totalValue := 0
for _, v := range m { for _, v := range m {
totalValue += v.(int) totalValue += v.(int)
@ -559,7 +559,7 @@ func ExampleIntAnyMap_RLockFunc() {
4: 4, 4: 4,
}) })
m.RLockFunc(func(m map[int]interface{}) { m.RLockFunc(func(m map[int]any) {
totalValue := 0 totalValue := 0
for _, v := range m { for _, v := range m {
totalValue += v.(int) totalValue += v.(int)
@ -651,7 +651,7 @@ func ExampleIntAnyMap_UnmarshalJSON() {
func ExampleIntAnyMap_UnmarshalValue() { func ExampleIntAnyMap_UnmarshalValue() {
var m gmap.IntAnyMap var m gmap.IntAnyMap
goWeb := map[int]interface{}{ goWeb := map[int]any{
1: "goframe", 1: "goframe",
2: "gin", 2: "gin",
3: "echo", 3: "echo",

View File

@ -22,7 +22,7 @@ func ExampleListMap_Iterator() {
} }
var totalKey, totalValue int var totalKey, totalValue int
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
totalKey += k.(int) totalKey += k.(int)
totalValue += v.(int) totalValue += v.(int)
@ -44,7 +44,7 @@ func ExampleListMap_IteratorAsc() {
} }
var totalKey, totalValue int var totalKey, totalValue int
m.IteratorAsc(func(k interface{}, v interface{}) bool { m.IteratorAsc(func(k any, v any) bool {
totalKey += k.(int) totalKey += k.(int)
totalValue += v.(int) totalValue += v.(int)
@ -66,7 +66,7 @@ func ExampleListMap_IteratorDesc() {
} }
var totalKey, totalValue int var totalKey, totalValue int
m.IteratorDesc(func(k interface{}, v interface{}) bool { m.IteratorDesc(func(k any, v any) bool {
totalKey += k.(int) totalKey += k.(int)
totalValue += v.(int) totalValue += v.(int)
@ -188,7 +188,7 @@ func ExampleListMap_Set() {
func ExampleListMap_Sets() { func ExampleListMap_Sets() {
m := gmap.NewListMap() m := gmap.NewListMap()
addMap := make(map[interface{}]interface{}) addMap := make(map[any]any)
addMap["key1"] = "val1" addMap["key1"] = "val1"
addMap["key2"] = "val2" addMap["key2"] = "val2"
addMap["key3"] = "val3" addMap["key3"] = "val3"
@ -291,10 +291,10 @@ func ExampleListMap_GetOrSetFunc() {
m := gmap.NewListMap() m := gmap.NewListMap()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetOrSetFunc("key1", func() interface{} { fmt.Println(m.GetOrSetFunc("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetOrSetFunc("key2", func() interface{} { fmt.Println(m.GetOrSetFunc("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -307,10 +307,10 @@ func ExampleListMap_GetOrSetFuncLock() {
m := gmap.NewListMap() m := gmap.NewListMap()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { fmt.Println(m.GetOrSetFuncLock("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { fmt.Println(m.GetOrSetFuncLock("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -347,10 +347,10 @@ func ExampleListMap_GetVarOrSetFunc() {
m := gmap.NewListMap() m := gmap.NewListMap()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { fmt.Println(m.GetVarOrSetFunc("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { fmt.Println(m.GetVarOrSetFunc("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -363,10 +363,10 @@ func ExampleListMap_GetVarOrSetFuncLock() {
m := gmap.NewListMap() m := gmap.NewListMap()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { fmt.Println(m.GetVarOrSetFuncLock("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { fmt.Println(m.GetVarOrSetFuncLock("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -389,10 +389,10 @@ func ExampleListMap_SetIfNotExist() {
func ExampleListMap_SetIfNotExistFunc() { func ExampleListMap_SetIfNotExistFunc() {
var m gmap.ListMap var m gmap.ListMap
fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { fmt.Println(m.SetIfNotExistFunc("k1", func() any {
return "v1" return "v1"
})) }))
fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { fmt.Println(m.SetIfNotExistFunc("k1", func() any {
return "v2" return "v2"
})) }))
fmt.Println(m.Map()) fmt.Println(m.Map())
@ -405,10 +405,10 @@ func ExampleListMap_SetIfNotExistFunc() {
func ExampleListMap_SetIfNotExistFuncLock() { func ExampleListMap_SetIfNotExistFuncLock() {
var m gmap.ListMap var m gmap.ListMap
fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { fmt.Println(m.SetIfNotExistFuncLock("k1", func() any {
return "v1" return "v1"
})) }))
fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { fmt.Println(m.SetIfNotExistFuncLock("k1", func() any {
return "v2" return "v2"
})) }))
fmt.Println(m.Map()) fmt.Println(m.Map())
@ -442,7 +442,7 @@ func ExampleListMap_Removes() {
"k4": "v4", "k4": "v4",
}) })
removeList := make([]interface{}, 2) removeList := make([]any, 2)
removeList = append(removeList, "k1") removeList = append(removeList, "k1")
removeList = append(removeList, "k2") removeList = append(removeList, "k2")

View File

@ -22,7 +22,7 @@ func ExampleStrAnyMap_Iterator() {
} }
var totalValue int var totalValue int
m.Iterator(func(k string, v interface{}) bool { m.Iterator(func(k string, v any) bool {
totalValue += v.(int) totalValue += v.(int)
return totalValue < 50 return totalValue < 50
@ -146,7 +146,7 @@ func ExampleStrAnyMap_Set() {
func ExampleStrAnyMap_Sets() { func ExampleStrAnyMap_Sets() {
m := gmap.NewStrAnyMap() m := gmap.NewStrAnyMap()
addMap := make(map[string]interface{}) addMap := make(map[string]any)
addMap["key1"] = "val1" addMap["key1"] = "val1"
addMap["key2"] = "val2" addMap["key2"] = "val2"
addMap["key3"] = "val3" addMap["key3"] = "val3"
@ -249,10 +249,10 @@ func ExampleStrAnyMap_GetOrSetFunc() {
m := gmap.NewStrAnyMap() m := gmap.NewStrAnyMap()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetOrSetFunc("key1", func() interface{} { fmt.Println(m.GetOrSetFunc("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetOrSetFunc("key2", func() interface{} { fmt.Println(m.GetOrSetFunc("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -265,10 +265,10 @@ func ExampleStrAnyMap_GetOrSetFuncLock() {
m := gmap.NewStrAnyMap() m := gmap.NewStrAnyMap()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { fmt.Println(m.GetOrSetFuncLock("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { fmt.Println(m.GetOrSetFuncLock("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -305,10 +305,10 @@ func ExampleStrAnyMap_GetVarOrSetFunc() {
m := gmap.NewStrAnyMap() m := gmap.NewStrAnyMap()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { fmt.Println(m.GetVarOrSetFunc("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { fmt.Println(m.GetVarOrSetFunc("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -321,10 +321,10 @@ func ExampleStrAnyMap_GetVarOrSetFuncLock() {
m := gmap.NewStrAnyMap() m := gmap.NewStrAnyMap()
m.Set("key1", "val1") m.Set("key1", "val1")
fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { fmt.Println(m.GetVarOrSetFuncLock("key1", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { fmt.Println(m.GetVarOrSetFuncLock("key2", func() any {
return "NotExistValue" return "NotExistValue"
})) }))
@ -347,10 +347,10 @@ func ExampleStrAnyMap_SetIfNotExist() {
func ExampleStrAnyMap_SetIfNotExistFunc() { func ExampleStrAnyMap_SetIfNotExistFunc() {
var m gmap.StrAnyMap var m gmap.StrAnyMap
fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { fmt.Println(m.SetIfNotExistFunc("k1", func() any {
return "v1" return "v1"
})) }))
fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { fmt.Println(m.SetIfNotExistFunc("k1", func() any {
return "v2" return "v2"
})) }))
fmt.Println(m.Map()) fmt.Println(m.Map())
@ -363,10 +363,10 @@ func ExampleStrAnyMap_SetIfNotExistFunc() {
func ExampleStrAnyMap_SetIfNotExistFuncLock() { func ExampleStrAnyMap_SetIfNotExistFuncLock() {
var m gmap.StrAnyMap var m gmap.StrAnyMap
fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { fmt.Println(m.SetIfNotExistFuncLock("k1", func() any {
return "v1" return "v1"
})) }))
fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { fmt.Println(m.SetIfNotExistFuncLock("k1", func() any {
return "v2" return "v2"
})) }))
fmt.Println(m.Map()) fmt.Println(m.Map())
@ -535,7 +535,7 @@ func ExampleStrAnyMap_LockFunc() {
"k4": 4, "k4": 4,
}) })
m.LockFunc(func(m map[string]interface{}) { m.LockFunc(func(m map[string]any) {
totalValue := 0 totalValue := 0
for _, v := range m { for _, v := range m {
totalValue += v.(int) totalValue += v.(int)
@ -556,7 +556,7 @@ func ExampleStrAnyMap_RLockFunc() {
"k4": 4, "k4": 4,
}) })
m.RLockFunc(func(m map[string]interface{}) { m.RLockFunc(func(m map[string]any) {
totalValue := 0 totalValue := 0
for _, v := range m { for _, v := range m {
totalValue += v.(int) totalValue += v.(int)
@ -648,7 +648,7 @@ func ExampleStrAnyMap_UnmarshalJSON() {
func ExampleStrAnyMap_UnmarshalValue() { func ExampleStrAnyMap_UnmarshalValue() {
var m gmap.StrAnyMap var m gmap.StrAnyMap
goWeb := map[string]interface{}{ goWeb := map[string]any{
"goframe": "https://goframe.org", "goframe": "https://goframe.org",
"gin": "https://gin-gonic.com/", "gin": "https://gin-gonic.com/",
"echo": "https://echo.labstack.com/", "echo": "https://echo.labstack.com/",

View File

@ -22,7 +22,7 @@ func ExampleNew() {
// Print size. // Print size.
fmt.Println(m.Size()) fmt.Println(m.Size())
addMap := make(map[interface{}]interface{}) addMap := make(map[any]any)
addMap["key2"] = "val2" addMap["key2"] = "val2"
addMap["key3"] = "val3" addMap["key3"] = "val3"
addMap[1] = 1 addMap[1] = 1
@ -46,7 +46,7 @@ func ExampleNew() {
fmt.Println(m.Keys()) fmt.Println(m.Keys())
// Batch remove keys. // Batch remove keys.
m.Removes([]interface{}{"key1", 1}) m.Removes([]any{"key1", 1})
fmt.Println(m.Keys()) fmt.Println(m.Keys())
// Contains checks whether a key exists. // Contains checks whether a key exists.

View File

@ -40,7 +40,7 @@ func Test_AnyAnyMap_Var(t *testing.T) {
t.AssertIN(3, m.Values()) t.AssertIN(3, m.Values())
t.AssertIN(1, m.Values()) t.AssertIN(1, m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]int{1: 1, 3: 3}) t.Assert(m.Map(), map[any]int{1: 1, 3: 3})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
@ -70,14 +70,14 @@ func Test_AnyAnyMap_Basic(t *testing.T) {
t.AssertIN(3, m.Values()) t.AssertIN(3, m.Values())
t.AssertIN(1, m.Values()) t.AssertIN(1, m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]int{1: 1, 3: 3}) t.Assert(m.Map(), map[any]int{1: 1, 3: 3})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
t.Assert(m.IsEmpty(), true) t.Assert(m.IsEmpty(), true)
m2 := gmap.NewAnyAnyMapFrom(map[interface{}]interface{}{1: 1, 2: "2"}) m2 := gmap.NewAnyAnyMapFrom(map[any]any{1: 1, 2: "2"})
t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, 2: "2"}) t.Assert(m2.Map(), map[any]any{1: 1, 2: "2"})
}) })
} }
@ -103,23 +103,23 @@ func Test_AnyAnyMap_Batch(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewAnyAnyMap() m := gmap.NewAnyAnyMap()
m.Sets(map[interface{}]interface{}{1: 1, 2: "2", 3: 3}) m.Sets(map[any]any{1: 1, 2: "2", 3: 3})
t.Assert(m.Map(), map[interface{}]interface{}{1: 1, 2: "2", 3: 3}) t.Assert(m.Map(), map[any]any{1: 1, 2: "2", 3: 3})
m.Removes([]interface{}{1, 2}) m.Removes([]any{1, 2})
t.Assert(m.Map(), map[interface{}]interface{}{3: 3}) t.Assert(m.Map(), map[any]any{3: 3})
}) })
} }
func Test_AnyAnyMap_Iterator_Deadlock(t *testing.T) { func Test_AnyAnyMap_Iterator_Deadlock(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewAnyAnyMapFrom(map[interface{}]interface{}{1: 1, 2: "2", "3": "3", "4": 4}, true) m := gmap.NewAnyAnyMapFrom(map[any]any{1: 1, 2: "2", "3": "3", "4": 4}, true)
m.Iterator(func(k interface{}, _ interface{}) bool { m.Iterator(func(k any, _ any) bool {
if gconv.Int(k)%2 == 0 { if gconv.Int(k)%2 == 0 {
m.Remove(k) m.Remove(k)
} }
return true return true
}) })
t.Assert(m.Map(), map[interface{}]interface{}{ t.Assert(m.Map(), map[any]any{
1: 1, 1: 1,
"3": "3", "3": "3",
}) })
@ -128,20 +128,20 @@ func Test_AnyAnyMap_Iterator_Deadlock(t *testing.T) {
func Test_AnyAnyMap_Iterator(t *testing.T) { func Test_AnyAnyMap_Iterator(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[interface{}]interface{}{1: 1, 2: "2"} expect := map[any]any{1: 1, 2: "2"}
m := gmap.NewAnyAnyMapFrom(expect) m := gmap.NewAnyAnyMapFrom(expect)
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
t.Assert(expect[k], v) t.Assert(expect[k], v)
return true return true
}) })
// 断言返回值对遍历控制 // 断言返回值对遍历控制
i := 0 i := 0
j := 0 j := 0
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
i++ i++
return true return true
}) })
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
j++ j++
return false return false
}) })
@ -152,12 +152,12 @@ func Test_AnyAnyMap_Iterator(t *testing.T) {
func Test_AnyAnyMap_Lock(t *testing.T) { func Test_AnyAnyMap_Lock(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[interface{}]interface{}{1: 1, 2: "2"} expect := map[any]any{1: 1, 2: "2"}
m := gmap.NewAnyAnyMapFrom(expect) m := gmap.NewAnyAnyMapFrom(expect)
m.LockFunc(func(m map[interface{}]interface{}) { m.LockFunc(func(m map[any]any) {
t.Assert(m, expect) t.Assert(m, expect)
}) })
m.RLockFunc(func(m map[interface{}]interface{}) { m.RLockFunc(func(m map[any]any) {
t.Assert(m, expect) t.Assert(m, expect)
}) })
}) })
@ -166,7 +166,7 @@ func Test_AnyAnyMap_Lock(t *testing.T) {
func Test_AnyAnyMap_Clone(t *testing.T) { func Test_AnyAnyMap_Clone(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
// clone 方法是深克隆 // clone 方法是深克隆
m := gmap.NewAnyAnyMapFrom(map[interface{}]interface{}{1: 1, 2: "2"}) m := gmap.NewAnyAnyMapFrom(map[any]any{1: 1, 2: "2"})
m_clone := m.Clone() m_clone := m.Clone()
m.Remove(1) m.Remove(1)
@ -186,7 +186,7 @@ func Test_AnyAnyMap_Merge(t *testing.T) {
m1.Set(1, 1) m1.Set(1, 1)
m2.Set(2, "2") m2.Set(2, "2")
m1.Merge(m2) m1.Merge(m2)
t.Assert(m1.Map(), map[interface{}]interface{}{1: 1, 2: "2"}) t.Assert(m1.Map(), map[any]any{1: 1, 2: "2"})
m3 := gmap.NewAnyAnyMapFrom(nil) m3 := gmap.NewAnyAnyMapFrom(nil)
m3.Merge(m2) m3.Merge(m2)
t.Assert(m3.Map(), m2.Map()) t.Assert(m3.Map(), m2.Map())
@ -366,7 +366,7 @@ func TestAnyAnyMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"k1":"v1","k2":"v2"}`), "map": []byte(`{"k1":"v1","k2":"v2"}`),
}, &v) }, &v)
@ -379,7 +379,7 @@ func TestAnyAnyMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.Map{ "map": g.Map{
"k1": "v1", "k1": "v1",
@ -438,8 +438,8 @@ func Test_AnyAnyMap_Diff(t *testing.T) {
4: "v4", 4: "v4",
}) })
addedKeys, removedKeys, updatedKeys := m1.Diff(m2) addedKeys, removedKeys, updatedKeys := m1.Diff(m2)
t.Assert(addedKeys, []interface{}{4}) t.Assert(addedKeys, []any{4})
t.Assert(removedKeys, []interface{}{"1"}) t.Assert(removedKeys, []any{"1"})
t.Assert(updatedKeys, []interface{}{3}) t.Assert(updatedKeys, []any{3})
}) })
} }

View File

@ -17,7 +17,7 @@ import (
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
) )
func getAny() interface{} { func getAny() any {
return 123 return 123
} }
@ -43,7 +43,7 @@ func Test_IntAnyMap_Var(t *testing.T) {
t.AssertIN(3, m.Values()) t.AssertIN(3, m.Values())
t.AssertIN(1, m.Values()) t.AssertIN(1, m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]int{1: 1, 3: 3}) t.Assert(m.Map(), map[any]int{1: 1, 3: 3})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
@ -73,20 +73,20 @@ func Test_IntAnyMap_Basic(t *testing.T) {
t.AssertIN(3, m.Values()) t.AssertIN(3, m.Values())
t.AssertIN(1, m.Values()) t.AssertIN(1, m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]int{1: 1, 3: 3}) t.Assert(m.Map(), map[any]int{1: 1, 3: 3})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
t.Assert(m.IsEmpty(), true) t.Assert(m.IsEmpty(), true)
m2 := gmap.NewIntAnyMapFrom(map[int]interface{}{1: 1, 2: "2"}) m2 := gmap.NewIntAnyMapFrom(map[int]any{1: 1, 2: "2"})
t.Assert(m2.Map(), map[int]interface{}{1: 1, 2: "2"}) t.Assert(m2.Map(), map[int]any{1: 1, 2: "2"})
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewIntAnyMap(true) m := gmap.NewIntAnyMap(true)
m.Set(1, 1) m.Set(1, 1)
t.Assert(m.Map(), map[int]interface{}{1: 1}) t.Assert(m.Map(), map[int]any{1: 1})
}) })
} }
@ -111,23 +111,23 @@ func Test_IntAnyMap_Batch(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewIntAnyMap() m := gmap.NewIntAnyMap()
m.Sets(map[int]interface{}{1: 1, 2: "2", 3: 3}) m.Sets(map[int]any{1: 1, 2: "2", 3: 3})
t.Assert(m.Map(), map[int]interface{}{1: 1, 2: "2", 3: 3}) t.Assert(m.Map(), map[int]any{1: 1, 2: "2", 3: 3})
m.Removes([]int{1, 2}) m.Removes([]int{1, 2})
t.Assert(m.Map(), map[int]interface{}{3: 3}) t.Assert(m.Map(), map[int]any{3: 3})
}) })
} }
func Test_IntAnyMap_Iterator_Deadlock(t *testing.T) { func Test_IntAnyMap_Iterator_Deadlock(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewIntAnyMapFrom(map[int]interface{}{1: 1, 2: 2, 3: "3", 4: 4}, true) m := gmap.NewIntAnyMapFrom(map[int]any{1: 1, 2: 2, 3: "3", 4: 4}, true)
m.Iterator(func(k int, _ interface{}) bool { m.Iterator(func(k int, _ any) bool {
if k%2 == 0 { if k%2 == 0 {
m.Remove(k) m.Remove(k)
} }
return true return true
}) })
t.Assert(m.Map(), map[int]interface{}{ t.Assert(m.Map(), map[int]any{
1: 1, 1: 1,
3: "3", 3: "3",
}) })
@ -136,20 +136,20 @@ func Test_IntAnyMap_Iterator_Deadlock(t *testing.T) {
func Test_IntAnyMap_Iterator(t *testing.T) { func Test_IntAnyMap_Iterator(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[int]interface{}{1: 1, 2: "2"} expect := map[int]any{1: 1, 2: "2"}
m := gmap.NewIntAnyMapFrom(expect) m := gmap.NewIntAnyMapFrom(expect)
m.Iterator(func(k int, v interface{}) bool { m.Iterator(func(k int, v any) bool {
t.Assert(expect[k], v) t.Assert(expect[k], v)
return true return true
}) })
// 断言返回值对遍历控制 // 断言返回值对遍历控制
i := 0 i := 0
j := 0 j := 0
m.Iterator(func(k int, v interface{}) bool { m.Iterator(func(k int, v any) bool {
i++ i++
return true return true
}) })
m.Iterator(func(k int, v interface{}) bool { m.Iterator(func(k int, v any) bool {
j++ j++
return false return false
}) })
@ -161,12 +161,12 @@ func Test_IntAnyMap_Iterator(t *testing.T) {
func Test_IntAnyMap_Lock(t *testing.T) { func Test_IntAnyMap_Lock(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[int]interface{}{1: 1, 2: "2"} expect := map[int]any{1: 1, 2: "2"}
m := gmap.NewIntAnyMapFrom(expect) m := gmap.NewIntAnyMapFrom(expect)
m.LockFunc(func(m map[int]interface{}) { m.LockFunc(func(m map[int]any) {
t.Assert(m, expect) t.Assert(m, expect)
}) })
m.RLockFunc(func(m map[int]interface{}) { m.RLockFunc(func(m map[int]any) {
t.Assert(m, expect) t.Assert(m, expect)
}) })
}) })
@ -175,7 +175,7 @@ func Test_IntAnyMap_Lock(t *testing.T) {
func Test_IntAnyMap_Clone(t *testing.T) { func Test_IntAnyMap_Clone(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
// clone 方法是深克隆 // clone 方法是深克隆
m := gmap.NewIntAnyMapFrom(map[int]interface{}{1: 1, 2: "2"}) m := gmap.NewIntAnyMapFrom(map[int]any{1: 1, 2: "2"})
m_clone := m.Clone() m_clone := m.Clone()
m.Remove(1) m.Remove(1)
@ -195,7 +195,7 @@ func Test_IntAnyMap_Merge(t *testing.T) {
m1.Set(1, 1) m1.Set(1, 1)
m2.Set(2, "2") m2.Set(2, "2")
m1.Merge(m2) m1.Merge(m2)
t.Assert(m1.Map(), map[int]interface{}{1: 1, 2: "2"}) t.Assert(m1.Map(), map[int]any{1: 1, 2: "2"})
m3 := gmap.NewIntAnyMapFrom(nil) m3 := gmap.NewIntAnyMapFrom(nil)
m3.Merge(m2) m3.Merge(m2)
t.Assert(m3.Map(), m2.Map()) t.Assert(m3.Map(), m2.Map())
@ -350,7 +350,7 @@ func TestIntAnyMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"1":"v1","2":"v2"}`), "map": []byte(`{"1":"v1","2":"v2"}`),
}, &v) }, &v)
@ -363,7 +363,7 @@ func TestIntAnyMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.MapIntAny{ "map": g.MapIntAny{
1: "v1", 1: "v1",

View File

@ -358,7 +358,7 @@ func TestIntIntMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"1":1,"2":2}`), "map": []byte(`{"1":1,"2":2}`),
}, &v) }, &v)
@ -371,7 +371,7 @@ func TestIntIntMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.MapIntAny{ "map": g.MapIntAny{
1: 1, 1: 1,

View File

@ -149,7 +149,7 @@ func Test_IntStrMap_Batch(t *testing.T) {
m.Sets(map[int]string{1: "a", 2: "b", 3: "c"}) m.Sets(map[int]string{1: "a", 2: "b", 3: "c"})
t.Assert(m.Map(), map[int]string{1: "a", 2: "b", 3: "c"}) t.Assert(m.Map(), map[int]string{1: "a", 2: "b", 3: "c"})
m.Removes([]int{1, 2}) m.Removes([]int{1, 2})
t.Assert(m.Map(), map[int]interface{}{3: "c"}) t.Assert(m.Map(), map[int]any{3: "c"})
}) })
} }
@ -384,7 +384,7 @@ func TestIntStrMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"1":"v1","2":"v2"}`), "map": []byte(`{"1":"v1","2":"v2"}`),
}, &v) }, &v)
@ -397,7 +397,7 @@ func TestIntStrMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.MapIntAny{ "map": g.MapIntAny{
1: "v1", 1: "v1",

View File

@ -41,7 +41,7 @@ func Test_StrAnyMap_Var(t *testing.T) {
t.AssertIN(1, m.Values()) t.AssertIN(1, m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[string]interface{}{"1": "a", "3": "c"}) t.Assert(m.Map(), map[string]any{"1": "a", "3": "c"})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
@ -72,14 +72,14 @@ func Test_StrAnyMap_Basic(t *testing.T) {
t.AssertIN(1, m.Values()) t.AssertIN(1, m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[string]interface{}{"1": "a", "3": "c"}) t.Assert(m.Map(), map[string]any{"1": "a", "3": "c"})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
t.Assert(m.IsEmpty(), true) t.Assert(m.IsEmpty(), true)
m2 := gmap.NewStrAnyMapFrom(map[string]interface{}{"a": 1, "b": "2"}) m2 := gmap.NewStrAnyMapFrom(map[string]any{"a": 1, "b": "2"})
t.Assert(m2.Map(), map[string]interface{}{"a": 1, "b": "2"}) t.Assert(m2.Map(), map[string]any{"a": 1, "b": "2"})
}) })
} }
@ -103,24 +103,24 @@ func Test_StrAnyMap_Batch(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewStrAnyMap() m := gmap.NewStrAnyMap()
m.Sets(map[string]interface{}{"a": 1, "b": "2", "c": 3}) m.Sets(map[string]any{"a": 1, "b": "2", "c": 3})
t.Assert(m.Map(), map[string]interface{}{"a": 1, "b": "2", "c": 3}) t.Assert(m.Map(), map[string]any{"a": 1, "b": "2", "c": 3})
m.Removes([]string{"a", "b"}) m.Removes([]string{"a", "b"})
t.Assert(m.Map(), map[string]interface{}{"c": 3}) t.Assert(m.Map(), map[string]any{"c": 3})
}) })
} }
func Test_StrAnyMap_Iterator_Deadlock(t *testing.T) { func Test_StrAnyMap_Iterator_Deadlock(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewStrAnyMapFrom(map[string]interface{}{"1": "1", "2": "2", "3": "3", "4": "4"}, true) m := gmap.NewStrAnyMapFrom(map[string]any{"1": "1", "2": "2", "3": "3", "4": "4"}, true)
m.Iterator(func(k string, _ interface{}) bool { m.Iterator(func(k string, _ any) bool {
kInt, _ := strconv.Atoi(k) kInt, _ := strconv.Atoi(k)
if kInt%2 == 0 { if kInt%2 == 0 {
m.Remove(k) m.Remove(k)
} }
return true return true
}) })
t.Assert(m.Map(), map[string]interface{}{ t.Assert(m.Map(), map[string]any{
"1": "1", "1": "1",
"3": "3", "3": "3",
}) })
@ -129,20 +129,20 @@ func Test_StrAnyMap_Iterator_Deadlock(t *testing.T) {
func Test_StrAnyMap_Iterator(t *testing.T) { func Test_StrAnyMap_Iterator(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[string]interface{}{"a": true, "b": false} expect := map[string]any{"a": true, "b": false}
m := gmap.NewStrAnyMapFrom(expect) m := gmap.NewStrAnyMapFrom(expect)
m.Iterator(func(k string, v interface{}) bool { m.Iterator(func(k string, v any) bool {
t.Assert(expect[k], v) t.Assert(expect[k], v)
return true return true
}) })
// 断言返回值对遍历控制 // 断言返回值对遍历控制
i := 0 i := 0
j := 0 j := 0
m.Iterator(func(k string, v interface{}) bool { m.Iterator(func(k string, v any) bool {
i++ i++
return true return true
}) })
m.Iterator(func(k string, v interface{}) bool { m.Iterator(func(k string, v any) bool {
j++ j++
return false return false
}) })
@ -153,13 +153,13 @@ func Test_StrAnyMap_Iterator(t *testing.T) {
func Test_StrAnyMap_Lock(t *testing.T) { func Test_StrAnyMap_Lock(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[string]interface{}{"a": true, "b": false} expect := map[string]any{"a": true, "b": false}
m := gmap.NewStrAnyMapFrom(expect) m := gmap.NewStrAnyMapFrom(expect)
m.LockFunc(func(m map[string]interface{}) { m.LockFunc(func(m map[string]any) {
t.Assert(m, expect) t.Assert(m, expect)
}) })
m.RLockFunc(func(m map[string]interface{}) { m.RLockFunc(func(m map[string]any) {
t.Assert(m, expect) t.Assert(m, expect)
}) })
}) })
@ -168,7 +168,7 @@ func Test_StrAnyMap_Lock(t *testing.T) {
func Test_StrAnyMap_Clone(t *testing.T) { func Test_StrAnyMap_Clone(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
// clone 方法是深克隆 // clone 方法是深克隆
m := gmap.NewStrAnyMapFrom(map[string]interface{}{"a": 1, "b": "2"}) m := gmap.NewStrAnyMapFrom(map[string]any{"a": 1, "b": "2"})
m_clone := m.Clone() m_clone := m.Clone()
m.Remove("a") m.Remove("a")
@ -188,7 +188,7 @@ func Test_StrAnyMap_Merge(t *testing.T) {
m1.Set("a", 1) m1.Set("a", 1)
m2.Set("b", "2") m2.Set("b", "2")
m1.Merge(m2) m1.Merge(m2)
t.Assert(m1.Map(), map[string]interface{}{"a": 1, "b": "2"}) t.Assert(m1.Map(), map[string]any{"a": 1, "b": "2"})
m3 := gmap.NewStrAnyMapFrom(nil) m3 := gmap.NewStrAnyMapFrom(nil)
m3.Merge(m2) m3.Merge(m2)
@ -358,7 +358,7 @@ func TestStrAnyMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"k1":"v1","k2":"v2"}`), "map": []byte(`{"k1":"v1","k2":"v2"}`),
}, &v) }, &v)
@ -371,7 +371,7 @@ func TestStrAnyMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.Map{ "map": g.Map{
"k1": "v1", "k1": "v1",

View File

@ -363,7 +363,7 @@ func TestStrIntMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"k1":1,"k2":2}`), "map": []byte(`{"k1":1,"k2":2}`),
}, &v) }, &v)
@ -376,7 +376,7 @@ func TestStrIntMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.Map{ "map": g.Map{
"k1": 1, "k1": 1,

View File

@ -362,7 +362,7 @@ func TestStrStrMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"k1":"v1","k2":"v2"}`), "map": []byte(`{"k1":"v1","k2":"v2"}`),
}, &v) }, &v)
@ -375,7 +375,7 @@ func TestStrStrMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.Map{ "map": g.Map{
"k1": "v1", "k1": "v1",

View File

@ -21,7 +21,7 @@ func Test_ListMap_Var(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var m gmap.ListMap var m gmap.ListMap
m.Set("key1", "val1") m.Set("key1", "val1")
t.Assert(m.Keys(), []interface{}{"key1"}) t.Assert(m.Keys(), []any{"key1"})
t.Assert(m.Get("key1"), "val1") t.Assert(m.Get("key1"), "val1")
t.Assert(m.Size(), 1) t.Assert(m.Size(), 1)
@ -41,7 +41,7 @@ func Test_ListMap_Var(t *testing.T) {
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
@ -53,7 +53,7 @@ func Test_ListMap_Basic(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewListMap() m := gmap.NewListMap()
m.Set("key1", "val1") m.Set("key1", "val1")
t.Assert(m.Keys(), []interface{}{"key1"}) t.Assert(m.Keys(), []any{"key1"})
t.Assert(m.Get("key1"), "val1") t.Assert(m.Get("key1"), "val1")
t.Assert(m.Size(), 1) t.Assert(m.Size(), 1)
@ -73,14 +73,14 @@ func Test_ListMap_Basic(t *testing.T) {
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
t.Assert(m.IsEmpty(), true) t.Assert(m.IsEmpty(), true)
m2 := gmap.NewListMapFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) m2 := gmap.NewListMapFrom(map[any]any{1: 1, "key1": "val1"})
t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"})
}) })
} }
@ -100,30 +100,30 @@ func Test_ListMap_Set_Fun(t *testing.T) {
func Test_ListMap_Batch(t *testing.T) { func Test_ListMap_Batch(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewListMap() m := gmap.NewListMap()
m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"})
t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"})
m.Removes([]interface{}{"key1", 1}) m.Removes([]any{"key1", 1})
t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"})
}) })
} }
func Test_ListMap_Iterator(t *testing.T) { func Test_ListMap_Iterator(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[interface{}]interface{}{1: 1, "key1": "val1"} expect := map[any]any{1: 1, "key1": "val1"}
m := gmap.NewListMapFrom(expect) m := gmap.NewListMapFrom(expect)
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
t.Assert(expect[k], v) t.Assert(expect[k], v)
return true return true
}) })
// 断言返回值对遍历控制 // 断言返回值对遍历控制
i := 0 i := 0
j := 0 j := 0
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
i++ i++
return true return true
}) })
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
j++ j++
return false return false
}) })
@ -135,7 +135,7 @@ func Test_ListMap_Iterator(t *testing.T) {
func Test_ListMap_Clone(t *testing.T) { func Test_ListMap_Clone(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
// clone 方法是深克隆 // clone 方法是深克隆
m := gmap.NewListMapFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) m := gmap.NewListMapFrom(map[any]any{1: 1, "key1": "val1"})
m_clone := m.Clone() m_clone := m.Clone()
m.Remove(1) m.Remove(1)
// 修改原 map,clone 后的 map 不影响 // 修改原 map,clone 后的 map 不影响
@ -154,7 +154,7 @@ func Test_ListMap_Basic_Merge(t *testing.T) {
m1.Set("key1", "val1") m1.Set("key1", "val1")
m2.Set("key2", "val2") m2.Set("key2", "val2")
m1.Merge(m2) m1.Merge(m2)
t.Assert(m1.Map(), map[interface{}]interface{}{"key1": "val1", "key2": "val2"}) t.Assert(m1.Map(), map[any]any{"key1": "val1", "key2": "val2"})
m3 := gmap.NewListMapFrom(nil) m3 := gmap.NewListMapFrom(nil)
m3.Merge(m2) m3.Merge(m2)
t.Assert(m3.Map(), m2.Map()) t.Assert(m3.Map(), m2.Map())
@ -321,7 +321,7 @@ func TestListMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"1":"v1","2":"v2"}`), "map": []byte(`{"1":"v1","2":"v2"}`),
}, &v) }, &v)
@ -334,7 +334,7 @@ func TestListMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.MapIntAny{ "map": g.MapIntAny{
1: "v1", 1: "v1",

View File

@ -22,7 +22,7 @@ func Test_TreeMap_Var(t *testing.T) {
var m gmap.TreeMap var m gmap.TreeMap
m.SetComparator(gutil.ComparatorString) m.SetComparator(gutil.ComparatorString)
m.Set("key1", "val1") m.Set("key1", "val1")
t.Assert(m.Keys(), []interface{}{"key1"}) t.Assert(m.Keys(), []any{"key1"})
t.Assert(m.Get("key1"), "val1") t.Assert(m.Get("key1"), "val1")
t.Assert(m.Size(), 1) t.Assert(m.Size(), 1)
@ -42,7 +42,7 @@ func Test_TreeMap_Var(t *testing.T) {
t.AssertIN("val1", m.Values()) t.AssertIN("val1", m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
@ -54,7 +54,7 @@ func Test_TreeMap_Basic(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewTreeMap(gutil.ComparatorString) m := gmap.NewTreeMap(gutil.ComparatorString)
m.Set("key1", "val1") m.Set("key1", "val1")
t.Assert(m.Keys(), []interface{}{"key1"}) t.Assert(m.Keys(), []any{"key1"})
t.Assert(m.Get("key1"), "val1") t.Assert(m.Get("key1"), "val1")
t.Assert(m.Size(), 1) t.Assert(m.Size(), 1)
@ -74,14 +74,14 @@ func Test_TreeMap_Basic(t *testing.T) {
t.AssertIN("val1", m.Values()) t.AssertIN("val1", m.Values())
m.Flip() m.Flip()
t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"})
m.Clear() m.Clear()
t.Assert(m.Size(), 0) t.Assert(m.Size(), 0)
t.Assert(m.IsEmpty(), true) t.Assert(m.IsEmpty(), true)
m2 := gmap.NewTreeMapFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) m2 := gmap.NewTreeMapFrom(gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"})
t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"})
}) })
} }
@ -101,29 +101,29 @@ func Test_TreeMap_Set_Fun(t *testing.T) {
func Test_TreeMap_Batch(t *testing.T) { func Test_TreeMap_Batch(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
m := gmap.NewTreeMap(gutil.ComparatorString) m := gmap.NewTreeMap(gutil.ComparatorString)
m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"})
t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"})
m.Removes([]interface{}{"key1", 1}) m.Removes([]any{"key1", 1})
t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"})
}) })
} }
func Test_TreeMap_Iterator(t *testing.T) { func Test_TreeMap_Iterator(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[interface{}]interface{}{1: 1, "key1": "val1"} expect := map[any]any{1: 1, "key1": "val1"}
m := gmap.NewTreeMapFrom(gutil.ComparatorString, expect) m := gmap.NewTreeMapFrom(gutil.ComparatorString, expect)
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
t.Assert(expect[k], v) t.Assert(expect[k], v)
return true return true
}) })
// 断言返回值对遍历控制 // 断言返回值对遍历控制
i := 0 i := 0
j := 0 j := 0
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
i++ i++
return true return true
}) })
m.Iterator(func(k interface{}, v interface{}) bool { m.Iterator(func(k any, v any) bool {
j++ j++
return false return false
}) })
@ -132,17 +132,17 @@ func Test_TreeMap_Iterator(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
expect := map[interface{}]interface{}{1: 1, "key1": "val1"} expect := map[any]any{1: 1, "key1": "val1"}
m := gmap.NewTreeMapFrom(gutil.ComparatorString, expect) m := gmap.NewTreeMapFrom(gutil.ComparatorString, expect)
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
m.IteratorAsc(func(k interface{}, v interface{}) bool { m.IteratorAsc(func(k any, v any) bool {
t.Assert(expect[k], v) t.Assert(expect[k], v)
return true return true
}) })
} }
j := 0 j := 0
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
m.IteratorAsc(func(k interface{}, v interface{}) bool { m.IteratorAsc(func(k any, v any) bool {
j++ j++
return false return false
}) })
@ -154,7 +154,7 @@ func Test_TreeMap_Iterator(t *testing.T) {
func Test_TreeMap_Clone(t *testing.T) { func Test_TreeMap_Clone(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
// clone 方法是深克隆 // clone 方法是深克隆
m := gmap.NewTreeMapFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) m := gmap.NewTreeMapFrom(gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"})
m_clone := m.Clone() m_clone := m.Clone()
m.Remove(1) m.Remove(1)
// 修改原 map,clone 后的 map 不影响 // 修改原 map,clone 后的 map 不影响
@ -218,7 +218,7 @@ func TestTreeMap_UnmarshalValue(t *testing.T) {
// JSON // JSON
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": []byte(`{"k1":"v1","k2":"v2"}`), "map": []byte(`{"k1":"v1","k2":"v2"}`),
}, &v) }, &v)
@ -231,7 +231,7 @@ func TestTreeMap_UnmarshalValue(t *testing.T) {
// Map // Map
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
var v *V var v *V
err := gconv.Struct(map[string]interface{}{ err := gconv.Struct(map[string]any{
"name": "john", "name": "john",
"map": g.Map{ "map": g.Map{
"k1": "v1", "k1": "v1",

View File

@ -21,28 +21,28 @@ import (
// Pool is an Object-Reusable Pool. // Pool is an Object-Reusable Pool.
type Pool struct { type Pool struct {
list *glist.List // Available/idle items list. list *glist.List // Available/idle items list.
closed *gtype.Bool // Whether the pool is closed. closed *gtype.Bool // Whether the pool is closed.
TTL time.Duration // Time To Live for pool items. TTL time.Duration // Time To Live for pool items.
NewFunc func() (interface{}, error) // Callback function to create pool item. NewFunc func() (any, error) // Callback function to create pool item.
// ExpireFunc is the function for expired items destruction. // ExpireFunc is the function for expired items destruction.
// This function needs to be defined when the pool items // This function needs to be defined when the pool items
// need to perform additional destruction operations. // need to perform additional destruction operations.
// Eg: net.Conn, os.File, etc. // Eg: net.Conn, os.File, etc.
ExpireFunc func(interface{}) ExpireFunc func(any)
} }
// Pool item. // Pool item.
type poolItem struct { type poolItem struct {
value interface{} // Item value. value any // Item value.
expireAt int64 // Expire timestamp in milliseconds. expireAt int64 // Expire timestamp in milliseconds.
} }
// NewFunc Creation function for object. // NewFunc Creation function for object.
type NewFunc func() (interface{}, error) type NewFunc func() (any, error)
// ExpireFunc Destruction function for object. // ExpireFunc Destruction function for object.
type ExpireFunc func(interface{}) type ExpireFunc func(any)
// New creates and returns a new object pool. // New creates and returns a new object pool.
// To ensure execution efficiency, the expiration time cannot be modified once it is set. // To ensure execution efficiency, the expiration time cannot be modified once it is set.
@ -66,7 +66,7 @@ func New(ttl time.Duration, newFunc NewFunc, expireFunc ...ExpireFunc) *Pool {
} }
// Put puts an item to pool. // Put puts an item to pool.
func (p *Pool) Put(value interface{}) error { func (p *Pool) Put(value any) error {
if p.closed.Val() { if p.closed.Val() {
return gerror.NewCode(gcode.CodeInvalidOperation, "pool is closed") return gerror.NewCode(gcode.CodeInvalidOperation, "pool is closed")
} }
@ -85,7 +85,7 @@ func (p *Pool) Put(value interface{}) error {
} }
// MustPut puts an item to pool, it panics if any error occurs. // MustPut puts an item to pool, it panics if any error occurs.
func (p *Pool) MustPut(value interface{}) { func (p *Pool) MustPut(value any) {
if err := p.Put(value); err != nil { if err := p.Put(value); err != nil {
panic(err) panic(err)
} }
@ -108,7 +108,7 @@ func (p *Pool) Clear() {
// Get picks and returns an item from pool. If the pool is empty and NewFunc is defined, // Get picks and returns an item from pool. If the pool is empty and NewFunc is defined,
// it creates and returns one from NewFunc. // it creates and returns one from NewFunc.
func (p *Pool) Get() (interface{}, error) { func (p *Pool) Get() (any, error) {
for !p.closed.Val() { for !p.closed.Val() {
if r := p.list.PopFront(); r != nil { if r := p.list.PopFront(); r != nil {
f := r.(*poolItem) f := r.(*poolItem)
@ -166,10 +166,7 @@ func (p *Pool) checkExpireItems(ctx context.Context) {
// by comparing with this timestamp. It is not accurate comparison for // by comparing with this timestamp. It is not accurate comparison for
// every item expired, but high performance. // every item expired, but high performance.
var timestampMilli = gtime.TimestampMilli() var timestampMilli = gtime.TimestampMilli()
for { for latestExpire <= timestampMilli {
if latestExpire > timestampMilli {
break
}
if r := p.list.PopFront(); r != nil { if r := p.list.PopFront(); r != nil {
item := r.(*poolItem) item := r.(*poolItem)
latestExpire = item.expireAt latestExpire = item.expireAt

View File

@ -20,11 +20,11 @@ func ExampleNew() {
} }
dbConnPool := gpool.New(time.Hour, dbConnPool := gpool.New(time.Hour,
func() (interface{}, error) { func() (any, error) {
dbConn := new(DBConn) dbConn := new(DBConn)
return dbConn, nil return dbConn, nil
}, },
func(i interface{}) { func(i any) {
// sample : close db conn // sample : close db conn
// i.(DBConn).Conn.Close() // i.(DBConn).Conn.Close()
}) })
@ -42,12 +42,12 @@ func ExamplePool_Put() {
} }
dbConnPool := gpool.New(time.Hour, dbConnPool := gpool.New(time.Hour,
func() (interface{}, error) { func() (any, error) {
dbConn := new(DBConn) dbConn := new(DBConn)
dbConn.Limit = 10 dbConn.Limit = 10
return dbConn, nil return dbConn, nil
}, },
func(i interface{}) { func(i any) {
// sample : close db conn // sample : close db conn
// i.(DBConn).Conn.Close() // i.(DBConn).Conn.Close()
}) })
@ -76,12 +76,12 @@ func ExamplePool_Clear() {
} }
dbConnPool := gpool.New(time.Hour, dbConnPool := gpool.New(time.Hour,
func() (interface{}, error) { func() (any, error) {
dbConn := new(DBConn) dbConn := new(DBConn)
dbConn.Limit = 10 dbConn.Limit = 10
return dbConn, nil return dbConn, nil
}, },
func(i interface{}) { func(i any) {
i.(*DBConn).Limit = 0 i.(*DBConn).Limit = 0
// sample : close db conn // sample : close db conn
// i.(DBConn).Conn.Close() // i.(DBConn).Conn.Close()
@ -106,12 +106,12 @@ func ExamplePool_Get() {
} }
dbConnPool := gpool.New(time.Hour, dbConnPool := gpool.New(time.Hour,
func() (interface{}, error) { func() (any, error) {
dbConn := new(DBConn) dbConn := new(DBConn)
dbConn.Limit = 10 dbConn.Limit = 10
return dbConn, nil return dbConn, nil
}, },
func(i interface{}) { func(i any) {
// sample : close db conn // sample : close db conn
// i.(DBConn).Conn.Close() // i.(DBConn).Conn.Close()
}) })
@ -132,12 +132,12 @@ func ExamplePool_Size() {
} }
dbConnPool := gpool.New(time.Hour, dbConnPool := gpool.New(time.Hour,
func() (interface{}, error) { func() (any, error) {
dbConn := new(DBConn) dbConn := new(DBConn)
dbConn.Limit = 10 dbConn.Limit = 10
return dbConn, nil return dbConn, nil
}, },
func(i interface{}) { func(i any) {
// sample : close db conn // sample : close db conn
// i.(DBConn).Conn.Close() // i.(DBConn).Conn.Close()
}) })
@ -159,12 +159,12 @@ func ExamplePool_Close() {
Limit int Limit int
} }
var ( var (
newFunc = func() (interface{}, error) { newFunc = func() (any, error) {
dbConn := new(DBConn) dbConn := new(DBConn)
dbConn.Limit = 10 dbConn.Limit = 10
return dbConn, nil return dbConn, nil
} }
closeFunc = func(i interface{}) { closeFunc = func(i any) {
fmt.Println("Close The Pool") fmt.Println("Close The Pool")
// sample : close db conn // sample : close db conn
// i.(DBConn).Conn.Close() // i.(DBConn).Conn.Close()

View File

@ -17,13 +17,13 @@ import (
"github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/test/gtest"
) )
var nf gpool.NewFunc = func() (i interface{}, e error) { var nf gpool.NewFunc = func() (i any, e error) {
return "hello", nil return "hello", nil
} }
var assertIndex = gtype.NewInt(0) var assertIndex = gtype.NewInt(0)
var ef gpool.ExpireFunc = func(i interface{}) { var ef gpool.ExpireFunc = func(i any) {
assertIndex.Add(1) assertIndex.Add(1)
gtest.Assert(i, assertIndex) gtest.Assert(i, assertIndex)
} }
@ -100,7 +100,7 @@ func Test_Gpool(t *testing.T) {
}) })
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
p := gpool.New(time.Millisecond*200, nil, func(i interface{}) {}) p := gpool.New(time.Millisecond*200, nil, func(i any) {})
p.Put(1) p.Put(1)
time.Sleep(time.Millisecond * 100) time.Sleep(time.Millisecond * 100)
p.Put(2) p.Put(2)
@ -109,7 +109,7 @@ func Test_Gpool(t *testing.T) {
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
s := make([]int, 0) s := make([]int, 0)
p := gpool.New(time.Millisecond*200, nil, func(i interface{}) { p := gpool.New(time.Millisecond*200, nil, func(i any) {
s = append(s, i.(int)) s = append(s, i.(int))
}) })
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {

Some files were not shown because too many files have changed in this diff Show More