Is it possible to misuse Kernel.to_string, from a security or fault inducing perspective?

I put this under chat/ discussions as this does not regard a bug, just some design/best practices.

I have program that I am building as per an exercise, and I want to use Kernel.to_string so that I don’t have to check a type later down the line.

The data being converted to string is simply going onto a table, and is being obtained from a keyword list. If the get on the keyword list yields nil the to_string will yield an empty string, and I’m fine with that.

I did not want to use inspect, as this is for logging/debugging and it seems there could be some security consequences down the line if I get into the habit of using inspect in this way, since it processes special terms and sigils.

to_string seems quite powerful, and it’s going to cut down a lot of code that I didn’t want to write and which would have seemed a bit repetitive, but should I be using it in this way?

Hey @DidactMacros your distinction between inspect and to_string is dead on. inspect is dangerous precisely because it can give away potentially significant information. to_string however is designed to be used exactly the way you’re using it. Types that have a canonical, user facing string representation will just work!


Thanks a lot, that’s great to know. Full steam ahead then.

Iirc, this happens under the hood anytime you use #{} interpolation


That’s right, the relevant docs:

Strings in Elixir also support interpolation. This allows you to place some value in the middle of a string by using the #{} syntax […]

Any Elixir expression is valid inside the interpolation. If a string is given, the string is interpolated as is. If any other value is given, Elixir will attempt to convert it to a string using the String.Chars protocol. This allows, for example, to output an integer from the interpolation

1 Like

What does this bit mean?

1 Like

I mean that I want to convert the data to a string if it is a compatible data type for the to_string function, rather than identifying and converting it through guards or cases.

The data is being obtained through list[key] from a keyword list, if nil is yielded I will get an empty string, which is what I want.

If any functions or incompatible types are sent through, it would throw an error, I’m not expecting that, but a runtime error seemed appropriate for such an occurrence.

Should I try to handle that differently?