Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ const val QWERTY_GLIDE_CANDIDATE_TYPE: Byte = 45
const val CANDIDATE_TYPE_USER_TEMPLATE: Byte = 46
const val CANDIDATE_TYPE_TIME: Byte = 47
const val CANDIDATE_TYPE_ERA: Byte = 48
const val CANDIDATE_TYPE_CALCULATION: Byte = 49
const val CANDIDATE_TYPE_UNIT_CONVERSION: Byte = 50
const val CANDIDATE_TYPE_UTILITY_LITERAL: Byte = 51

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.kazumaproject.markdownhelperkeyboard.converter.utility

import java.math.BigDecimal
import java.math.MathContext
import java.math.RoundingMode

object ResultFormatter {
private const val AUTO_DIGITS = 15
private const val SCIENTIFIC_UPPER_EXPONENT = 12
private const val SCIENTIFIC_LOWER_EXPONENT = -7

@Suppress("DEPRECATION")
fun format(value: BigDecimal, precision: Precision): String {
if (value.signum() == 0) return "0"
val rounded = when (precision) {
Precision.Auto -> {
if (value.precision() > AUTO_DIGITS) {
value.round(MathContext(AUTO_DIGITS, RoundingMode.HALF_UP))
} else {
value
}
}
Precision.Integer -> value.setScale(0, RoundingMode.HALF_UP)
is Precision.DecimalPlaces -> value.setScale(
precision.places,
RoundingMode.HALF_UP,
)
is Precision.SignificantDigits -> value.round(
MathContext(precision.digits, RoundingMode.HALF_UP)
)
}.stripTrailingZeros()
if (rounded.signum() == 0) return "0"

val exponent = rounded.precision() - rounded.scale() - 1
return if (exponent >= SCIENTIFIC_UPPER_EXPONENT || exponent <= SCIENTIFIC_LOWER_EXPONENT) {
val mantissa = rounded.movePointLeft(exponent).stripTrailingZeros().toPlainString()
"$mantissa" + "e" + exponent
} else {
rounded.toPlainString()
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package com.kazumaproject.markdownhelperkeyboard.converter.utility

import java.math.BigDecimal
import java.math.MathContext
import java.math.RoundingMode

data class ParsedUnitExpression(
val category: UnitCategory,
val baseValue: BigDecimal,
val terms: List<ParsedUnitTerm>,
val canonicalSourceText: String,
val prefersCanonicalSource: Boolean,
)

data class ParsedUnitTerm(
val value: BigDecimal,
val unit: UnitDefinition,
)

class UnitExpressionParser(
private val registry: UnitRegistry = UnitRegistry.Default,
private val maxTerms: Int = 128,
) {
private val context = MathContext(50, RoundingMode.HALF_EVEN)

fun parse(
expression: String,
profile: RegionalUnitProfile = RegionalUnitProfile.JAPAN,
): ParsedUnitExpression? {
val rewritten = rewriteJapaneseTemperature(expression.trim())
val source = rewritten.text
if (source.isEmpty()) return null
var offset = 0
var category: UnitCategory? = null
var baseValue = BigDecimal.ZERO
val terms = mutableListOf<ParsedUnitTerm>()
val canonicalSource = StringBuilder(source.length)
var prefersCanonicalSource = rewritten.wasRewritten

while (true) {
offset = skipSpaces(source, offset)
if (offset >= source.length) break
var sign = 1
var operator = ""
when (source[offset]) {
'+' -> {
if (terms.isNotEmpty()) operator = "+"
offset++
offset = skipSpaces(source, offset)
}
'-' -> {
sign = -1
operator = "-"
offset++
offset = skipSpaces(source, offset)
}
}

val numberStart = offset
val number = readNumber(source, offset) ?: return null
offset = number.end
offset = skipSpaces(source, offset)
val match = registry.matchAt(source, offset, category, profile) ?: return null
offset += match.length

val unit = match.definition
if (category == null) category = unit.category
if (unit.category != category) return null
val signedValue = if (sign < 0) number.value.negate() else number.value
terms += ParsedUnitTerm(signedValue, unit)
canonicalSource.append(operator)
canonicalSource.append(source, numberStart, number.end)
canonicalSource.append(unit.symbol)
prefersCanonicalSource = prefersCanonicalSource || match.isWordAlias
if (terms.size > maxTerms) return null

if (category == UnitCategory.TEMPERATURE && terms.size > 1) return null
baseValue = if (category == UnitCategory.TEMPERATURE) {
unit.toBase(signedValue, context)
} else {
baseValue.add(unit.toBase(signedValue, context), context)
}

offset = skipSpaces(source, offset)
if (offset >= source.length) break
val next = source[offset]
if (next != '+' && next != '-' && !next.isDigit() && next != '.') return null
}

return ParsedUnitExpression(
category = category ?: return null,
baseValue = baseValue,
terms = terms,
canonicalSourceText = canonicalSource.toString(),
prefersCanonicalSource = prefersCanonicalSource,
)
}

private data class NumberRead(val value: BigDecimal, val end: Int)

private fun readNumber(source: String, start: Int): NumberRead? {
var offset = start
var digits = 0
var integerDigits = 0
while (source.getOrNull(offset)?.isDigit() == true) {
offset++
digits++
integerDigits++
}
if (integerDigits > 0) {
var consumedGrouping = false
while (source.getOrNull(offset) == ',') {
val groupStart = offset + 1
var groupLength = 0
while (source.getOrNull(groupStart + groupLength)?.isDigit() == true) groupLength++
if (groupLength != 3 || (!consumedGrouping && integerDigits !in 1..3)) break
consumedGrouping = true
offset += 4
digits += 3
}
}
if (source.getOrNull(offset) == '.') {
offset++
while (source.getOrNull(offset)?.isDigit() == true) {
offset++
digits++
}
}
if (digits == 0 || digits > MAX_LITERAL_DIGITS) return null
val exponentStart = offset
if (source.getOrNull(offset) == 'e' || source.getOrNull(offset) == 'E') {
var probe = offset + 1
if (source.getOrNull(probe) == '+' || source.getOrNull(probe) == '-') probe++
val exponentDigits = probe
while (source.getOrNull(probe)?.isDigit() == true) probe++
if (probe > exponentDigits) {
if (probe - exponentDigits > 6) return null
offset = probe
} else {
offset = exponentStart
}
}
val value = source.substring(start, offset).replace(",", "").toBigDecimalOrNull()
?: return null
return NumberRead(value, offset)
}

private data class RewrittenSource(val text: String, val wasRewritten: Boolean)

private fun rewriteJapaneseTemperature(source: String): RewrittenSource {
val match = JAPANESE_TEMPERATURE.matchEntire(source)
?: return RewrittenSource(source, false)
val unit = if (match.groupValues[1] == "華氏") "°F" else "°C"
return RewrittenSource(match.groupValues[2] + unit, true)
}

private fun skipSpaces(source: String, start: Int): Int {
var offset = start
while (source.getOrNull(offset)?.isWhitespace() == true) offset++
return offset
}

private companion object {
const val MAX_LITERAL_DIGITS = 64
val JAPANESE_TEMPERATURE = Regex(
"^(華氏|摂氏)\\s*([+-]?(?:\\d+(?:,\\d{3})*|\\d*\\.\\d+)(?:[eE][+-]?\\d+)?)\\s*度?$"
)
}
}
Loading
Loading