Is there a specific reason there is no `fun String...
# squarelibraries
m
Is there a specific reason there is no
fun String.source(): Source
like there is
fun File.source(): Source
?
Copy code
// This works
File(path).source().buffer()
// This doesn't
"Hello World".source().buffer()
Writing
Buffer().write("Hello World")
works but it breaks the typing flow
j
Well for one a string is not a source of bytes it's a source of characters
So you'd need an encoding step or at minimum to specify the charset for encoding
m
I'm ok with
fun String.source(charset: Charset = Charsets.UTF_8): Source
Also had a similar question for
ByteString.source()
And
Charset
is not MPP, I see...
I'd still use
String.utf8Source()
and
ByteString.source()
j
Generally the thought is that things which are sources of data and not data itself have the extension
👀 1
m
Fair enough. Something else I realized is that Strings and ByteStrings can be reused while Sources can't so I guess not having the extension highlights that behaviour
j
I'm reluctant to do this cause I don't like APIs where you need to change syntax when you add complexity
m
What kind of complexity are you thinking of?
j
For example here, once we can convert a string to a Source, if you grow your string things get ugly...
Copy code
val s = """1\n2\n3\n"""
return s.toSource()
That's your ideal case, but then we refactor some:
Copy code
val s = buildString {
  for (i in 1..3)
    append(i.toString())
    append("\n")
  }
}
return s.toSource()
In general the 2nd example performs terribly compared to building a Buffer. It allocates lots of intermediate Strings and then needs to UTF-8 transcode to go back into bytes. Optimal here is where the more verbose API leads you:
Copy code
return Buffer().apply {
   for (i in 1..3)
     writeDecimalLong(i)
     writeUtf8("\n")
   }
 }
👍 1
✔️ 1
m
Ah yes, thanks! That makes sense.
Asking because I have an API that works with
BufferedSource
mainly and that provides convenience overloads to work with
String
and
ByteString
and it's a bit painful to define these overloads everywhere...
But maybe the overloads aren't that used. I'll double check
j
We generally have one overload
👀 1
For example, Moshi takes a String or BufferedSource but not ByteString
Wire takes a byte[] or BufferedSource