diff options
Diffstat (limited to 'src/tools/clippy/src/docs/string_lit_as_bytes.txt')
-rw-r--r-- | src/tools/clippy/src/docs/string_lit_as_bytes.txt | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/src/tools/clippy/src/docs/string_lit_as_bytes.txt b/src/tools/clippy/src/docs/string_lit_as_bytes.txt new file mode 100644 index 000000000..a125b97ed --- /dev/null +++ b/src/tools/clippy/src/docs/string_lit_as_bytes.txt @@ -0,0 +1,39 @@ +### What it does +Checks for the `as_bytes` method called on string literals +that contain only ASCII characters. + +### Why is this bad? +Byte string literals (e.g., `b"foo"`) can be used +instead. They are shorter but less discoverable than `as_bytes()`. + +### Known problems +`"str".as_bytes()` and the suggested replacement of `b"str"` are not +equivalent because they have different types. The former is `&[u8]` +while the latter is `&[u8; 3]`. That means in general they will have a +different set of methods and different trait implementations. + +``` +fn f(v: Vec<u8>) {} + +f("...".as_bytes().to_owned()); // works +f(b"...".to_owned()); // does not work, because arg is [u8; 3] not Vec<u8> + +fn g(r: impl std::io::Read) {} + +g("...".as_bytes()); // works +g(b"..."); // does not work +``` + +The actual equivalent of `"str".as_bytes()` with the same type is not +`b"str"` but `&b"str"[..]`, which is a great deal of punctuation and not +more readable than a function call. + +### Example +``` +let bstr = "a byte string".as_bytes(); +``` + +Use instead: +``` +let bstr = b"a byte string"; +```
\ No newline at end of file |