go-tools icon indicating copy to clipboard operation
go-tools copied to clipboard

simple: check uneeded []byte or []string conversion for len builtin

Open martisch opened this issue 5 years ago • 10 comments

Converting a string or []byte to the other type to compute the length is not needed.

Example: https://github.com/golang/net/blob/0ba52f642ac2f9371a88bfdde41f4b4e195a37c0/dns/dnsmessage/message.go#L1848

martisch avatar May 22 '20 06:05 martisch

Looks like a typo in the title. Not []byte or []string, but []byte or string.

Antonboom avatar Nov 16 '24 19:11 Antonboom

+ json.RawMessage conversion

Antonboom avatar Nov 17 '24 07:11 Antonboom

Indeed,

len([]byte(...: 6.5k

len(string(: 5.4k (but they are struct with stringer among them)

len(json.RawMessage(...: 4

ccoVeille avatar Nov 17 '24 07:11 ccoVeille

@Antonboom

Does the code you tried when playing with testifylint around len(string( and len([]byte( could be used to help to provide the linter needed here

ccoVeille avatar Nov 17 '24 16:11 ccoVeille

could be used to help to provide the linter needed here

I don't mind if it makes sense.

Antonboom avatar Nov 17 '24 16:11 Antonboom

My question was somehow to ask you if you plan to open a PR for fixing this issue

ccoVeille avatar Nov 17 '24 16:11 ccoVeille

you plan to open a PR for fixing this issue

I don't plan to, it's out of my focus at the moment. My apologies 🙏

Antonboom avatar Nov 17 '24 17:11 Antonboom

you plan to open a PR for fixing this issue

I don't plan to, it's out of my focus at the moment. My apologies 🙏

It's OK, so I know I can work on it if I find time

ccoVeille avatar Nov 17 '24 17:11 ccoVeille

ruleguard pattern:

func lenStrByteSlice(m dsl.Matcher) {
	// len(string([]byte)) -> len([]byte)
	m.Match(`len(string($b))`).
		Where(m["b"].Type.Underlying().Is("[]byte")).
		Report(`Call len() on the byte slice instead of converting to a string first`).
		Suggest(`len($b)`)
}

func lenByteSliceStr(m dsl.Matcher) {
	// len([]byte(string)) -> len(string)
	m.Match(`len([]byte($s))`).
		Where(m["s"].Type.Underlying().Is("string")).
		Report(`Call len() on the string instead of converting to []byte first.`).
		Suggest(`len($s)`)
}

dgryski avatar Nov 17 '24 21:11 dgryski

Thanks @dgryski

I should give a try at rule guard at some point !

ccoVeille avatar Nov 17 '24 22:11 ccoVeille