Make Regex class serializable on JVM

#KT-16447 Fixed

Refactor helper functions for serialization tests.
This commit is contained in:
Ilya Gorbunov
2017-04-22 02:24:17 +03:00
parent 99bd54116e
commit 16d3d2f764
6 changed files with 80 additions and 13 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -95,7 +95,7 @@ public data class MatchGroup(public val value: String, public val range: IntRang
*/
public class Regex
@PublishedApi
internal constructor(private val nativePattern: Pattern) {
internal constructor(private val nativePattern: Pattern) : Serializable {
/** Creates a regular expression from the specified [pattern] string and the default options. */
@@ -112,8 +112,9 @@ internal constructor(private val nativePattern: Pattern) {
public val pattern: String
get() = nativePattern.pattern()
private var _options: Set<RegexOption>? = null
/** The set of options that were used to create this regular expression. */
public val options: Set<RegexOption> = fromInt(nativePattern.flags())
public val options: Set<RegexOption> get() = _options ?: fromInt<RegexOption>(nativePattern.flags()).also { _options = it }
/** Indicates whether the regular expression matches the entire [input]. */
public infix fun matches(input: CharSequence): Boolean = nativePattern.matcher(input).matches()
@@ -203,6 +204,16 @@ internal constructor(private val nativePattern: Pattern) {
*/
public fun toPattern(): Pattern = nativePattern
private fun writeReplace(): Any = Serialized(nativePattern.pattern(), nativePattern.flags())
private class Serialized(val pattern: String, val flags: Int) : Serializable {
companion object {
private const val serialVersionUID: Long = 0L
}
private fun readResolve(): Any = Regex(Pattern.compile(pattern, flags))
}
companion object {
/** Returns a literal regex for the specified [literal] string. */
public fun fromLiteral(literal: String): Regex = literal.toRegex(RegexOption.LITERAL)