Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce new StringProperties object that can encode and decode properties from a string #2303

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

petitcl
Copy link

@petitcl petitcl commented May 14, 2023

Introduce a new StringProperties object that can encode and decode properties from a string format. This new object is heavily based on the existing kotlinx.serialization Properties object.

  • for encoding, it first encodes the input Kotlin object a string map using Properties and them formats that string map to a properties file. Some parameters can be passed to customise the encoding format, such as key/value separator, number of spaces before and after the key/value separator, and line separator.
  • for decoding, it first parses the input data as a string map and then decodes it into a Kotlin object using Properties. The parsers handles comments, whitespaces, escapes, natural lines vs logical lines. The intent is to support the same format as the Java Properties API (doc). For now, unicode characters are not implemented.

The implementation has been inspired a lot from the gist made by https://github.com/RaphaelTarita linked in this issue. I have added many unit tests that show how it is used and how it behaves.

This PR should fix #1152 and KT-42716.

@ExperimentalSerializationApi
public override fun <T> encodeToString(serializer: SerializationStrategy<T>, value: T): String {
val map = properties.encodeToMap(serializer, value)
val builder = StringBuilder()
Copy link
Contributor

@hfhbd hfhbd Jan 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would extract the actual output renderer into another function taking a map overload to encode a giving String map to a Properties file

@ExperimentalSerializationApi
public fun encodeToString(map: Map<String, String>): String {


result[parsedLine.substring(0, keyEnd)] = parsedLine.substring(valueBegin)
}
return properties.decodeFromStringMap(deserializer, result)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, I would add an overload to get the input string as Map<String, String too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Properties should support String encoding/decoding
2 participants