major migration part 4
- Commit
25297f033225f470e587e660ad397d6b892cf88e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-31 20:20 UTC (4 months ago)
- Parents
7d74de2
Diff
astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/SolarAndPlanetaryTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/SolarAndPlanetaryTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/SolarAndPlanetaryTest.ktindex 82bf3c6def..a9b3156941 100644--- a/astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/SolarAndPlanetaryTest.kt+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/domain/engine/SolarAndPlanetaryTest.kt@@ -14,7 +14,7 @@ class SolarAndPlanetaryTest { // At J2000 sun RA ~ 18h45m ~ 281 deg, Dec ~ -23 deg (approx solstice offset?) Actually J2000 sun was at ~280 deg lon // We check that our calc doesn't explode and dec in [-24,24] val sun = SolarCalculator.calc(TimeEngine.J2000)- assertTrue(sun.raDec.decDeg in -24.0..24.0, "sun dec ${sun.decDeg}")+ assertTrue(sun.raDec.decDeg in -24.0..24.0, "sun dec ${sun.raDec.decDeg}") assertTrue(sun.distanceAu in 0.97..1.03) }
calendar/src/main/java/com/vayunmathur/calendar/util/RRule.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/RRule.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/RRule.ktindex 42419fe78b..788b46a42a 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/RRule.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/RRule.kt@@ -48,6 +48,12 @@ private fun RRule.EndCondition.describeSuffix(context: Context): String = when ( is RRule.EndCondition.Until -> context.getString(R.string.rrule_until_suffix, date.format(dateFormat)) } +private fun RRule.EndCondition.toStringSuffix(): String = when (this) {+ is RRule.EndCondition.Never -> ""+ is RRule.EndCondition.Count -> ", $count times"+ is RRule.EndCondition.Until -> ", Until ${date.format(dateFormat)}"+}+ @Serializable sealed class RRule { abstract val endCondition: EndCondition@@ -64,6 +70,11 @@ sealed class RRule { } protected abstract fun describeImpl(context: Context): String + protected abstract fun toStringImpl(): String+ final override fun toString(): String {+ return toStringImpl() + endCondition.toStringSuffix()+ }+ companion object { fun parse(content: String, timeZone: TimeZone): RRule? { if (content.isBlank()) return null@@ -191,6 +202,8 @@ sealed class RRule { override fun describeImpl(context: Context): String = if (years == 1) context.getString(R.string.rrule_yearly) else context.resources.getQuantityString(R.plurals.rrule_every_years, years, years)++ override fun toStringImpl(): String = if (years == 1) "Yearly" else "Every $years years" } @Serializable@@ -222,6 +235,8 @@ sealed class RRule { override fun describeImpl(context: Context): String = if (months == 1) context.getString(R.string.rrule_monthly) else context.resources.getQuantityString(R.plurals.rrule_every_months, months, months)++ override fun toStringImpl(): String = if (months == 1) "Monthly" else "Every $months months" } @Serializable@@ -251,6 +266,15 @@ sealed class RRule { } return context.getString(R.string.rrule_on_days, prefix, days) }++ override fun toStringImpl(): String {+ val prefix = if (weeks == 1) "Weekly" else "Every $weeks weeks"+ if (daysOfWeek.isEmpty()) return prefix+ val days = daysOfWeek.sorted().joinToString(", ") {+ it.name.take(3).lowercase().replaceFirstChar { c -> c.titlecase() }+ }+ return "$prefix on $days"+ } } @Serializable@@ -272,5 +296,7 @@ sealed class RRule { override fun describeImpl(context: Context): String = if (days == 1) context.getString(R.string.rrule_daily) else context.resources.getQuantityString(R.plurals.rrule_every_days, days, days)++ override fun toStringImpl(): String = if (days == 1) "Daily" else "Every $days days" } }\ No newline at end of file
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 622ccce229..c04ddb374d 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -77,12 +77,14 @@ brotli = "0.1.2" # THIRD PARTY # ============================================================================= -# Networking (Square)-okio = "3.17.0" # isolated: contacts/files VCF+zip + messages MetaMqtt/Signal/WhatsApp ByteString – NOT networking-okhttp = "4.12.0" # isolated: media3-datasource-okhttp (youpipe player) + Vonage SDK (dooraccess)--# Images-androidsvg = "1.4"+# Networking (Square) – Android policy is HttpURLConnection + library:network only (no new OkHttp/Ktor deps)+# okio/okhttp remain isolated exceptions where upstream SDKs require them:+# - maps: MapLibre Android SDK requires OkHttp Call.Factory via HttpRequestUtil.setOkHttpClient (MapTileCache) – already on runtime classpath via maplibre android-sdk+# - messages: Meta Messenger/Instagram MQTT+WS (ByteString framing), Signal WebSocket+HTTP (cert pinning), WhatsApp NOISE/WebSocket – HTTP parts use library:network where possible, WS kept as exception+# - personal/dooraccess (conditional, gitignored): Vonage SDK transitive okhttp (plus conditional include settings.gradle.kts:95-102)+# contacts/files/appstore/youpipe have been migrated off okio/okhttp to java.io BufferedReader/Writer + ZipFile + HttpURLConnection/DefaultHttpDataSource+okio = "3.17.0" # isolated: messages WS ByteString + transitive via okhttp (maps, dooraccess) – contacts/files/appstore/youpipe migrated to java.io + library:network+okhttp = "4.12.0" # isolated: maps MapLibre Call.Factory + messages Meta/Signal/WA + dooraccess Vonage – appstore/youpipe migrated to HttpURLConnection/DefaultHttpDataSource # Maps & geospatial maplibre = "0.13.0"@@ -172,7 +174,6 @@ androidx-media3-exoplayer = { module = "androidx.media3:media3-exoplayer", versi androidx-media3-exoplayer-dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "media3Exoplayer" } androidx-media3-session = { module = "androidx.media3:media3-session", version.ref = "media3Exoplayer" } androidx-media3-ui-compose-material3 = { module = "androidx.media3:media3-ui-compose-material3", version.ref = "media3Exoplayer" }-androidx-media3-datasource-okhttp = { group = "androidx.media3", name = "media3-datasource-okhttp", version.ref = "media3Exoplayer" } # AndroidX – CameraX & images androidx-camera-core = { group = "androidx.camera", name = "camera-core", version.ref = "camerax" }@@ -230,12 +231,9 @@ brotli-dec = { module = "org.brotli:dec", version.ref = "brotli" } # THIRD PARTY # ============================================================================= -# Networking (Square)-okio = { group = "com.squareup.okio", name = "okio", version.ref = "okio" } # isolated: contacts/files + messages ByteString-okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } # isolated: media3-datasource-okhttp + Vonage SDK--# SVG image decoding via library:image (replaces coil-svg)-androidsvg = { module = "com.caverock:androidsvg-aar", version.ref = "androidsvg" }+# Networking (Square) – isolated exceptions only: maps MapLibre Call.Factory, messages Meta/Signal/WA WS, dooraccess Vonage+okio = { group = "com.squareup.okio", name = "okio", version.ref = "okio" } # isolated: messages MetaMqtt/Signal/WhatsApp ByteString (OkHttp WS API) + transitive via okhttp (maps, dooraccess) – contacts/files migrated to java.io+okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } # isolated: maps MapLibre Call.Factory + messages Meta/Signal/WA + dooraccess Vonage – appstore/youpipe migrated # Maps & geospatial maplibre-compose = { module = "org.maplibre.compose:maplibre-compose", version.ref = "maplibre" }
library/image/build.gradle.kts
diff --git a/library/image/build.gradle.kts b/library/image/build.gradle.ktsindex 649974251b..41d28d94ea 100644--- a/library/image/build.gradle.kts+++ b/library/image/build.gradle.kts@@ -9,8 +9,7 @@ dependencies { // Coroutines implementation(libs.kotlinx.coroutines.android) - // SVG rendering – replaces coil-svg- implementation(libs.androidsvg)+ // SVG rendering is now internal via Android stdlib (Canvas/Path/Paint/XmlPullParser) – no third-party // Foundation needed for Image composable in AsyncImage implementation(libs.androidx.compose.foundation)
library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt b/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.ktindex 294a869632..920b9f6377 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt@@ -21,7 +21,7 @@ import kotlinx.coroutines.withContext * - [MemoryCache] (LruCache<String, Bitmap>) * - [DiskCache] (file LRU raw bytes) * - Fetcher registry (http/content/file/asset/bytearray/bitmap)- * - Decoders: SVG via androidsvg, Video via MediaMetadataRetriever, Bitmap via BitmapFactory/ImageDecoder+ * - Decoders: SVG via internal Android stdlib renderer (Canvas/Path), Video via MediaMetadataRetriever, Bitmap via BitmapFactory/ImageDecoder */ class ImageLoader private constructor( private val appContext: Context,
library/image/src/main/java/com/vayunmathur/library/image/decoders/SvgDecoder.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/decoders/SvgDecoder.kt b/library/image/src/main/java/com/vayunmathur/library/image/decoders/SvgDecoder.ktindex 6460cd84e7..84cbb9e1de 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/decoders/SvgDecoder.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/decoders/SvgDecoder.kt@@ -3,10 +3,31 @@ package com.vayunmathur.library.image.decoders import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color-import com.caverock.androidsvg.SVG+import android.graphics.Matrix+import android.graphics.Paint+import android.graphics.Path+import android.graphics.RectF import com.vayunmathur.library.image.ImageRequest-import java.io.ByteArrayInputStream+import org.xmlpull.v1.XmlPullParser+import org.xmlpull.v1.XmlPullParserFactory+import java.io.StringReader+import java.util.ArrayDeque+import kotlin.math.abs+import kotlin.math.atan2+import kotlin.math.ceil+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt+import kotlin.math.tan +/**+ * Pure Android stdlib SVG decoder – own implementation.+ *+ * Only uses:+ * - android.graphics.* (Bitmap, Canvas, Paint, Path, Matrix, Color) – Android stdlib+ * - org.xmlpull.v1.XmlPullParser (Android runtime XML parser, part of Android stdlib)+ * - Kotlin stdlib / JetBrains stdlib (regex, math)+ */ object SvgDecoder { fun canDecode(bytes: ByteArray, dataHint: Any?): Boolean {@@ -19,45 +40,380 @@ object SvgDecoder { suspend fun decode(bytes: ByteArray, request: ImageRequest): Bitmap? { return try {- val svg = SVG.getFromInputStream(ByteArrayInputStream(bytes))+ val svgString = try { String(bytes, Charsets.UTF_8) } catch (_: Exception) { String(bytes, Charsets.ISO_8859_1) }+ val rootInfo = parseSvgRoot(svgString) val reqSize = request.size val targetW = if (reqSize != null && !reqSize.isOriginal()) reqSize.width else 512 val targetH = if (reqSize != null && !reqSize.isOriginal()) reqSize.height else 512-- // Determine document dimensions- val docW = svg.documentWidth- val docH = svg.documentHeight+ val docW = rootInfo.docWidth+ val docH = rootInfo.docHeight val aspect: Float = if (docW > 0 && docH > 0) docW / docH else 1f- val outW: Int val outH: Int- if (targetW > 0 && targetH > 0) {- outW = targetW- outH = targetH- } else if (targetW > 0) {- outW = targetW- outH = (targetW / aspect).toInt().coerceAtLeast(1)- } else if (docW > 0 && docH > 0) {- outW = docW.toInt().coerceAtLeast(1)- outH = docH.toInt().coerceAtLeast(1)- } else {- outW = 512- outH = 512- }--// If doc has no size, set a viewport so it scales- if (docW <= 0 || docH <= 0) {- svg.setDocumentWidth(outW.toFloat())- svg.setDocumentHeight(outH.toFloat())- }+ if (targetW > 0 && targetH > 0) { outW = targetW; outH = targetH }+ else if (targetW > 0) { outW = targetW; outH = (targetW / aspect).toInt().coerceAtLeast(1) }+ else if (docW > 0 && docH > 0) { outW = docW.toInt().coerceAtLeast(1); outH = docH.toInt().coerceAtLeast(1) }+ else { outW = 512; outH = 512 } val bitmap = Bitmap.createBitmap(outW, outH, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) canvas.drawColor(Color.TRANSPARENT)- svg.renderToCanvas(canvas)+ renderSvgToCanvas(canvas, svgString, outW, outH, rootInfo) bitmap- } catch (_: Exception) {- null+ } catch (_: Exception) { null }+ }+}++// --- internal models ---++private data class ViewBox(val minX: Float, val minY: Float, val width: Float, val height: Float)+private data class RootInfo(val docWidth: Float, val docHeight: Float, val viewBox: ViewBox?)+private data class EffectiveStyle(+ val fill: String?, val fillOpacity: Float, val stroke: String?, val strokeOpacity: Float,+ val strokeWidth: Float, val strokeLineCap: String, val strokeLineJoin: String,+ val strokeMiterLimit: Float, val fillRule: String, val display: String?, val visibility: String?,+ val effectiveOpacity: Float+) {+ companion object { fun default() = EffectiveStyle("black", 1f, null, 1f, 1f, "butt", "miter", 4f, "nonzero", null, null, 1f) }+}++private val leadingNumberRegex = Regex("""^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?""")+private val numberRegex = Regex("""[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?""")++private fun parseLength(v: String?): Float? {+ if (v == null) return null+ val s = v.trim(); if (s.isEmpty()) return null+ return leadingNumberRegex.find(s)?.value?.toFloatOrNull()+}+private fun parseDocLength(v: String?): Float? {+ if (v == null) return null+ val s = v.trim(); if (s.isEmpty() || s.contains("%")) return null+ return leadingNumberRegex.find(s)?.value?.toFloatOrNull()+}+private fun parseViewBox(vb: String?): ViewBox? {+ if (vb == null) return null+ val parts = vb.replace(',', ' ').trim().split(Regex("\\s+")).mapNotNull { it.toFloatOrNull() }+ if (parts.size == 4 && parts[2] > 0 && parts[3] > 0) return ViewBox(parts[0], parts[1], parts[2], parts[3])+ return null+}+private fun parseNumbersList(s: String): List<Float> {+ if (s.isBlank()) return emptyList()+ return numberRegex.findAll(s).mapNotNull { it.value.toFloatOrNull() }.toList()+}+private fun parseStyleAttribute(style: String): Map<String, String> {+ val m = mutableMapOf<String, String>()+ for (decl in style.split(';')) {+ val t = decl.trim(); if (t.isEmpty()) continue+ val c = t.indexOf(':'); if (c <= 0) continue+ val prop = t.substring(0, c).trim().lowercase()+ val value = t.substring(c + 1).trim()+ if (prop.isNotEmpty() && value.isNotEmpty()) m[prop] = value+ }+ return m+}+private fun parseRgbComp(c: String): Int {+ val t = c.trim()+ return if (t.endsWith("%")) {+ val v = t.removeSuffix("%").toFloatOrNull() ?: 0f+ (v * 255f / 100f).toInt().coerceIn(0, 255)+ } else t.toFloatOrNull()?.toInt()?.coerceIn(0, 255) ?: 0+}+private fun parseAlphaComp(c: String): Float {+ val t = c.trim()+ return if (t.endsWith("%")) {+ val v = t.removeSuffix("%").toFloatOrNull() ?: 1f+ (v / 100f).coerceIn(0f, 1f)+ } else {+ val f = t.toFloatOrNull() ?: 1f+ if (f > 1f) (f / 255f).coerceIn(0f, 1f) else f.coerceIn(0f, 1f)+ }+}+private fun parseColorString(cs: String?): Int? {+ if (cs == null) return null+ val s = cs.trim(); if (s.isEmpty()) return null+ val lower = s.lowercase()+ if (lower == "none") return null+ if (lower == "transparent") return Color.TRANSPARENT+ if (lower == "currentcolor") return null+ if (lower.startsWith("#")) { try { return Color.parseColor(s) } catch (_: Exception) {} }+ if (lower.startsWith("rgb(") || lower.startsWith("rgba(")) {+ try {+ val inner = s.substringAfter('(').substringBeforeLast(')').replace('/', ' ').trim()+ val parts = inner.split(Regex("[\\s,]+")).filter { it.isNotEmpty() }+ if (parts.size >= 3) {+ val r = parseRgbComp(parts[0]); val g = parseRgbComp(parts[1]); val b = parseRgbComp(parts[2])+ val a = if (parts.size >= 4) parseAlphaComp(parts[3]) else 1f+ return Color.argb((a * 255).toInt().coerceIn(0, 255), r, g, b)+ }+ } catch (_: Exception) {}+ }+ try { return Color.parseColor(s) } catch (_: Exception) {+ return when (lower) {+ "red" -> Color.RED; "green" -> Color.GREEN; "blue" -> Color.BLUE+ "black" -> Color.BLACK; "white" -> Color.WHITE+ "gray", "grey" -> Color.GRAY; "yellow" -> Color.YELLOW+ "cyan", "aqua" -> Color.CYAN; "magenta", "fuchsia" -> Color.MAGENTA+ else -> null } } }+private fun parseTransform(tr: String?): Matrix? {+ if (tr.isNullOrBlank()) return null+ val result = Matrix(); result.reset()+ val regex = Regex("""([a-zA-Z]+)\s*\(([^)]*)\)""")+ var found = false+ for (m in regex.findAll(tr)) {+ val name = m.groupValues[1].trim().lowercase()+ val args = parseNumbersList(m.groupValues[2])+ val local = Matrix()+ when (name) {+ "matrix" -> { if (args.size >= 6) local.setValues(floatArrayOf(args[0], args[2], args[4], args[1], args[3], args[5], 0f, 0f, 1f)) else continue }+ "translate" -> when {+ args.size >= 2 -> local.setTranslate(args[0], args[1])+ args.size == 1 -> local.setTranslate(args[0], 0f)+ else -> continue+ }+ "scale" -> when {+ args.size >= 2 -> local.setScale(args[0], args[1])+ args.size == 1 -> local.setScale(args[0], args[0])+ else -> continue+ }+ "rotate" -> when {+ args.size >= 3 -> local.setRotate(args[0], args[1], args[2])+ args.size == 1 -> local.setRotate(args[0])+ else -> continue+ }+ "skewx" -> { if (args.isNotEmpty()) { val t = tan(Math.toRadians(args[0].toDouble())).toFloat(); local.setSkew(t, 0f) } else continue }+ "skewy" -> { if (args.isNotEmpty()) { val t = tan(Math.toRadians(args[0].toDouble())).toFloat(); local.setSkew(0f, t) } else continue }+ else -> continue+ }+ result.postConcat(local); found = true+ }+ return if (found) result else null+}+private fun computeEffective(parent: EffectiveStyle, attrs: Map<String, String>): EffectiveStyle {+ val rawFill = attrs["fill"]+ val fill: String? = when {+ rawFill == null -> parent.fill+ rawFill.equals("none", ignoreCase = true) -> null+ rawFill.equals("inherit", ignoreCase = true) -> parent.fill+ rawFill.equals("currentcolor", ignoreCase = true) -> parent.fill+ else -> rawFill+ }+ val fillOpacity = attrs["fill-opacity"]?.toFloatOrNull() ?: parent.fillOpacity+ val rawStroke = attrs["stroke"]+ val stroke: String? = when {+ rawStroke == null -> parent.stroke+ rawStroke.equals("none", ignoreCase = true) -> null+ rawStroke.equals("inherit", ignoreCase = true) -> parent.stroke+ rawStroke.equals("currentcolor", ignoreCase = true) -> parent.stroke+ else -> rawStroke+ }+ val strokeOpacity = attrs["stroke-opacity"]?.toFloatOrNull() ?: parent.strokeOpacity+ val strokeWidth = attrs["stroke-width"]?.let { parseLength(it) } ?: parent.strokeWidth+ val strokeLineCap = attrs["stroke-linecap"] ?: parent.strokeLineCap+ val strokeLineJoin = attrs["stroke-linejoin"] ?: parent.strokeLineJoin+ val strokeMiterLimit = attrs["stroke-miterlimit"]?.toFloatOrNull() ?: parent.strokeMiterLimit+ val fillRule = attrs["fill-rule"] ?: parent.fillRule+ val display = attrs["display"]+ val visibility = attrs["visibility"]+ val localOpacity = attrs["opacity"]?.toFloatOrNull() ?: 1f+ val eff = (parent.effectiveOpacity * localOpacity).coerceIn(0f, 1f)+ return EffectiveStyle(+ fill, fillOpacity.coerceIn(0f, 1f), stroke, strokeOpacity.coerceIn(0f, 1f),+ strokeWidth, strokeLineCap, strokeLineJoin, strokeMiterLimit, fillRule, display, visibility, eff+ )+}+private fun drawPathWithStyle(canvas: Canvas, path: Path, style: EffectiveStyle) {+ if (path.isEmpty) return+ path.fillType = if (style.fillRule.equals("evenodd", ignoreCase = true)) Path.FillType.EVEN_ODD else Path.FillType.WINDING+ if (style.fill != null) {+ val resolved = parseColorString(style.fill) ?: Color.BLACK+ val baseAlpha = Color.alpha(resolved) / 255f+ val finalAlpha = (baseAlpha * style.fillOpacity * style.effectiveOpacity * 255f).toInt().coerceIn(0, 255)+ if (finalAlpha > 0) {+ val finalColor = (finalAlpha shl 24) or (resolved and 0x00FFFFFF)+ val paint = Paint().apply { isAntiAlias = true; this.style = Paint.Style.FILL; color = finalColor }+ canvas.drawPath(path, paint)+ }+ }+ if (style.stroke != null && style.strokeWidth > 0.001f) {+ val resolved = parseColorString(style.stroke) ?: Color.BLACK+ val baseAlpha = Color.alpha(resolved) / 255f+ val finalAlpha = (baseAlpha * style.strokeOpacity * style.effectiveOpacity * 255f).toInt().coerceIn(0, 255)+ if (finalAlpha > 0) {+ val finalColor = (finalAlpha shl 24) or (resolved and 0x00FFFFFF)+ val paint = Paint().apply {+ isAntiAlias = true; this.style = Paint.Style.STROKE; color = finalColor; strokeWidth = style.strokeWidth+ strokeCap = when (style.strokeLineCap.lowercase()) { "round" -> Paint.Cap.ROUND; "square" -> Paint.Cap.SQUARE; else -> Paint.Cap.BUTT }+ strokeJoin = when (style.strokeLineJoin.lowercase()) { "round" -> Paint.Join.ROUND; "bevel" -> Paint.Join.BEVEL; else -> Paint.Join.MITER }+ strokeMiter = style.strokeMiterLimit+ }+ canvas.drawPath(path, paint)+ }+ }+}+private fun parseSvgRoot(svgContent: String): RootInfo {+ try {+ val factory = XmlPullParserFactory.newInstance(); factory.isNamespaceAware = false+ val parser = factory.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)+ parser.setInput(StringReader(svgContent))+ var event = parser.eventType+ while (event != XmlPullParser.END_DOCUMENT) {+ if (event == XmlPullParser.START_TAG && parser.name.equals("svg", ignoreCase = true)) {+ var docW = 0f; var docH = 0f; var vb: ViewBox? = null+ for (i in 0 until parser.attributeCount) {+ val an = parser.getAttributeName(i)?.lowercase(); val av = parser.getAttributeValue(i) ?: continue+ when (an) { "width" -> parseDocLength(av)?.let { docW = it }; "height" -> parseDocLength(av)?.let { docH = it }; "viewbox" -> vb = parseViewBox(av) }+ }+ if ((docW <= 0 || docH <= 0) && vb != null) { if (docW <= 0) docW = vb.width; if (docH <= 0) docH = vb.height }+ return RootInfo(docW, docH, vb)+ }+ event = parser.next()+ }+ } catch (_: Exception) {}+ return RootInfo(0f, 0f, null)+}+private fun renderSvgToCanvas(canvas: Canvas, svgContent: String, outW: Int, outH: Int, rootInfo: RootInfo) {+ val factory = XmlPullParserFactory.newInstance(); factory.isNamespaceAware = false+ val parser = factory.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)+ parser.setInput(StringReader(svgContent))+ val styleStack = ArrayDeque<EffectiveStyle>(); var currentStyle = EffectiveStyle.default()+ val canvasSaveStack = ArrayDeque<Int>(); var skipDepth: Int? = null+ val nonRendering = setOf("defs", "clippath", "mask", "pattern", "filter", "style", "script", "title", "desc", "metadata", "lineargradient", "radialgradient", "stop", "image")+ val baseSave = canvas.save()+ if (rootInfo.viewBox != null) {+ val vb = rootInfo.viewBox; val scaleX = outW / vb.width; val scaleY = outH / vb.height; val scale = kotlin.math.min(scaleX, scaleY)+ val scaledW = vb.width * scale; val scaledH = vb.height * scale+ val tx = (outW - scaledW) / 2f; val ty = (outH - scaledH) / 2f+ canvas.translate(tx, ty); canvas.scale(scale, scale); canvas.translate(-vb.minX, -vb.minY)+ } else if (rootInfo.docWidth > 0 && rootInfo.docHeight > 0) {+ val sx = outW / rootInfo.docWidth; val sy = outH / rootInfo.docHeight+ if (kotlin.math.abs(sx - 1f) > 0.001f || kotlin.math.abs(sy - 1f) > 0.001f) canvas.scale(sx, sy)+ }+ var eventType = parser.eventType+ while (eventType != XmlPullParser.END_DOCUMENT) {+ if (eventType == XmlPullParser.START_TAG) {+ val depth = parser.depth+ if (skipDepth != null && depth > skipDepth) { eventType = parser.next(); continue }+ val tagName = parser.name?.lowercase() ?: ""+ if (tagName in nonRendering) { skipDepth = depth; eventType = parser.next(); continue }+ val attrs = mutableMapOf<String, String>()+ for (i in 0 until parser.attributeCount) { val an = parser.getAttributeName(i)?.lowercase() ?: continue; val av = parser.getAttributeValue(i) ?: continue; attrs[an] = av }+ val styleAttr = attrs["style"]+ if (!styleAttr.isNullOrBlank()) { val sm = parseStyleAttribute(styleAttr); for ((k, v) in sm) attrs[k] = v; attrs.remove("style") }+ if (attrs["display"]?.trim()?.lowercase() == "none") { skipDepth = depth; eventType = parser.next(); continue }+ val vis = attrs["visibility"]?.trim()?.lowercase()+ if (vis == "hidden" || vis == "collapse") { skipDepth = depth; eventType = parser.next(); continue }+ val effective = computeEffective(parent = currentStyle, attrs = attrs)+ if (effective.effectiveOpacity <= 0.01f) { skipDepth = depth; eventType = parser.next(); continue }+ val saveCount = canvas.save(); canvasSaveStack.addLast(saveCount); styleStack.addLast(currentStyle); currentStyle = effective+ parseTransform(attrs["transform"])?.let { canvas.concat(it) }+ if (tagName == "svg" && depth > 1) {+ val nx = parseLength(attrs["x"]) ?: 0f; val ny = parseLength(attrs["y"]) ?: 0f; if (nx != 0f || ny != 0f) canvas.translate(nx, ny)+ val nestedVb = parseViewBox(attrs["viewbox"]); val nestedW = parseLength(attrs["width"]); val nestedH = parseLength(attrs["height"])+ if (nestedVb != null && nestedW != null && nestedH != null && nestedW > 0 && nestedH > 0) {+ val sx = nestedW / nestedVb.width; val sy = nestedH / nestedVb.height; val s = kotlin.math.min(sx, sy)+ val sw = nestedVb.width * s; val sh = nestedVb.height * s; val tx = (nestedW - sw) / 2f; val ty = (nestedH - sh) / 2f+ canvas.translate(tx, ty); canvas.scale(s, s); canvas.translate(-nestedVb.minX, -nestedVb.minY)+ } else if (nestedVb != null) { canvas.translate(-nestedVb.minX, -nestedVb.minY) }+ }+ try {+ when (tagName) {+ "path" -> { val d = attrs["d"]; if (!d.isNullOrBlank()) { val p = parsePathData(d); if (!p.isEmpty) drawPathWithStyle(canvas, p, currentStyle) } }+ "rect" -> {+ val x = parseLength(attrs["x"]) ?: 0f; val y = parseLength(attrs["y"]) ?: 0f; val w = parseLength(attrs["width"]) ?: 0f; val h = parseLength(attrs["height"]) ?: 0f+ if (w > 0 && h > 0) {+ val rx = parseLength(attrs["rx"]); val ry = parseLength(attrs["ry"]); val path = Path(); val rect = RectF(x, y, x + w, y + h)+ if ((rx != null && rx > 0) || (ry != null && ry > 0)) {+ val rxV = rx ?: ry ?: 0f; val ryV = ry ?: rx ?: 0f; val crx = rxV.coerceAtMost(w / 2f); val cry = ryV.coerceAtMost(h / 2f)+ path.addRoundRect(rect, crx, cry, Path.Direction.CW)+ } else path.addRect(rect, Path.Direction.CW)+ drawPathWithStyle(canvas, path, currentStyle)+ }+ }+ "circle" -> { val cx = parseLength(attrs["cx"]) ?: 0f; val cy = parseLength(attrs["cy"]) ?: 0f; val r = parseLength(attrs["r"]) ?: 0f; if (r > 0) { val path = Path(); path.addCircle(cx, cy, r, Path.Direction.CW); drawPathWithStyle(canvas, path, currentStyle) } }+ "ellipse" -> { val cx = parseLength(attrs["cx"]) ?: 0f; val cy = parseLength(attrs["cy"]) ?: 0f; val rx = parseLength(attrs["rx"]) ?: 0f; val ry = parseLength(attrs["ry"]) ?: 0f; if (rx > 0 && ry > 0) { val path = Path(); val oval = RectF(cx - rx, cy - ry, cx + rx, cy + ry); path.addOval(oval, Path.Direction.CW); drawPathWithStyle(canvas, path, currentStyle) } }+ "line" -> { val x1 = parseLength(attrs["x1"]) ?: 0f; val y1 = parseLength(attrs["y1"]) ?: 0f; val x2 = parseLength(attrs["x2"]) ?: 0f; val y2 = parseLength(attrs["y2"]) ?: 0f; val path = Path(); path.moveTo(x1, y1); path.lineTo(x2, y2); drawPathWithStyle(canvas, path, currentStyle) }+ "polyline" -> { val pts = attrs["points"]; if (!pts.isNullOrBlank()) { val nums = parseNumbersList(pts); if (nums.size >= 4) { val path = Path(); path.moveTo(nums[0], nums[1]); var i = 2; while (i + 1 < nums.size) { path.lineTo(nums[i], nums[i + 1]); i += 2 }; drawPathWithStyle(canvas, path, currentStyle) } } }+ "polygon" -> { val pts = attrs["points"]; if (!pts.isNullOrBlank()) { val nums = parseNumbersList(pts); if (nums.size >= 4) { val path = Path(); path.moveTo(nums[0], nums[1]); var i = 2; while (i + 1 < nums.size) { path.lineTo(nums[i], nums[i + 1]); i += 2 }; path.close(); drawPathWithStyle(canvas, path, currentStyle) } } }+ }+ } catch (_: Exception) {}+ } else if (eventType == XmlPullParser.END_TAG) {+ val depth = parser.depth+ if (skipDepth != null) { if (depth == skipDepth) skipDepth = null; eventType = parser.next(); continue }+ if (canvasSaveStack.isNotEmpty()) { val sc = canvasSaveStack.removeLast(); canvas.restoreToCount(sc) }+ if (styleStack.isNotEmpty()) { currentStyle = styleStack.removeLast() }+ }+ eventType = parser.next()+ }+ canvas.restoreToCount(baseSave)+}++private fun parsePathData(d: String): Path {+ val path = Path(); var i = 0; val n = d.length; var curX = 0f; var curY = 0f; var startX = 0f; var startY = 0f; var lastCubicX2 = 0f; var lastCubicY2 = 0f; var lastQuadX1 = 0f; var lastQuadY1 = 0f; var prevCmd: Char = ' '+ fun skipSeparators() { while (i < n && (d[i].isWhitespace() || d[i] == ',')) i++ }+ fun peekIsNumberStart(): Boolean { var j = i; while (j < n && (d[j].isWhitespace() || d[j] == ',')) j++; if (j >= n) return false; val c = d[j]; return c.isDigit() || c == '.' || c == '+' || c == '-' }+ fun parseNumber(): Float? { skipSeparators(); if (i >= n) return null; val sub = d.substring(i); val m = leadingNumberRegex.find(sub); if (m != null && m.range.first == 0) { val v = m.value.toFloatOrNull(); i += m.value.length; return v }; return null }+ fun parseFlag(): Int? { skipSeparators(); if (i >= n) return null; val c = d[i]; if (c == '0' || c == '1') { i++; return c - '0' }; return null }+ var cmd: Char = ' '+ while (i < n) {+ skipSeparators(); if (i >= n) break; val c = d[i]+ if (c in "MmZzLlHhVvCcSsQqTtAa") { cmd = c; i++ } else if (peekIsNumberStart() && cmd != ' ') {} else { i++; continue }+ val isRelative = cmd.isLowerCase()+ when (cmd.uppercaseChar()) {+ 'M' -> { var first = true; while (peekIsNumberStart()) { val x = parseNumber() ?: break; val y = parseNumber() ?: break; val nx = if (isRelative) curX + x else x; val ny = if (isRelative) curY + y else y; if (first) { path.moveTo(nx, ny); startX = nx; startY = ny; first = false } else path.lineTo(nx, ny); curX = nx; curY = ny; prevCmd = 'M' }; if (!first) cmd = if (isRelative) 'l' else 'L' }+ 'L' -> { while (peekIsNumberStart()) { val x = parseNumber() ?: break; val y = parseNumber() ?: break; val nx = if (isRelative) curX + x else x; val ny = if (isRelative) curY + y else y; path.lineTo(nx, ny); curX = nx; curY = ny; prevCmd = 'L' } }+ 'H' -> { while (peekIsNumberStart()) { val x = parseNumber() ?: break; curX = if (isRelative) curX + x else x; path.lineTo(curX, curY); prevCmd = 'H' } }+ 'V' -> { while (peekIsNumberStart()) { val y = parseNumber() ?: break; curY = if (isRelative) curY + y else y; path.lineTo(curX, curY); prevCmd = 'V' } }+ 'C' -> { while (peekIsNumberStart()) { val x1 = parseNumber() ?: break; val y1 = parseNumber() ?: break; val x2 = parseNumber() ?: break; val y2 = parseNumber() ?: break; val x = parseNumber() ?: break; val y = parseNumber() ?: break; val c1x = if (isRelative) curX + x1 else x1; val c1y = if (isRelative) curY + y1 else y1; val c2x = if (isRelative) curX + x2 else x2; val c2y = if (isRelative) curY + y2 else y2; val nx = if (isRelative) curX + x else x; val ny = if (isRelative) curY + y else y; path.cubicTo(c1x, c1y, c2x, c2y, nx, ny); lastCubicX2 = c2x; lastCubicY2 = c2y; curX = nx; curY = ny; prevCmd = 'C' } }+ 'S' -> { while (peekIsNumberStart()) { val x2 = parseNumber() ?: break; val y2 = parseNumber() ?: break; val x = parseNumber() ?: break; val y = parseNumber() ?: break; val c2x = if (isRelative) curX + x2 else x2; val c2y = if (isRelative) curY + y2 else y2; val nx = if (isRelative) curX + x else x; val ny = if (isRelative) curY + y else y; val c1x: Float; val c1y: Float; if (prevCmd.uppercaseChar() == 'C' || prevCmd.uppercaseChar() == 'S') { c1x = curX * 2 - lastCubicX2; c1y = curY * 2 - lastCubicY2 } else { c1x = curX; c1y = curY }; path.cubicTo(c1x, c1y, c2x, c2y, nx, ny); lastCubicX2 = c2x; lastCubicY2 = c2y; curX = nx; curY = ny; prevCmd = 'S' } }+ 'Q' -> { while (peekIsNumberStart()) { val x1 = parseNumber() ?: break; val y1 = parseNumber() ?: break; val x = parseNumber() ?: break; val y = parseNumber() ?: break; val c1x = if (isRelative) curX + x1 else x1; val c1y = if (isRelative) curY + y1 else y1; val nx = if (isRelative) curX + x else x; val ny = if (isRelative) curY + y else y; path.quadTo(c1x, c1y, nx, ny); lastQuadX1 = c1x; lastQuadY1 = c1y; curX = nx; curY = ny; prevCmd = 'Q' } }+ 'T' -> { while (peekIsNumberStart()) { val x = parseNumber() ?: break; val y = parseNumber() ?: break; val nx = if (isRelative) curX + x else x; val ny = if (isRelative) curY + y else y; val c1x: Float; val c1y: Float; if (prevCmd.uppercaseChar() == 'Q' || prevCmd.uppercaseChar() == 'T') { c1x = curX * 2 - lastQuadX1; c1y = curY * 2 - lastQuadY1 } else { c1x = curX; c1y = curY }; path.quadTo(c1x, c1y, nx, ny); lastQuadX1 = c1x; lastQuadY1 = c1y; curX = nx; curY = ny; prevCmd = 'T' } }+ 'A' -> {+ while (peekIsNumberStart()) {+ val rx = parseNumber() ?: break; val ry = parseNumber() ?: break; val ang = parseNumber() ?: break; val largeArc = parseFlag() ?: break; val sweep = parseFlag() ?: break; val x = parseNumber() ?: break; val y = parseNumber() ?: break+ val nx = if (isRelative) curX + x else x; val ny = if (isRelative) curY + y else y+ arcTo(path, curX, curY, rx, ry, ang, largeArc, sweep, nx, ny); curX = nx; curY = ny; prevCmd = 'A'+ }+ }+ 'Z' -> { path.close(); curX = startX; curY = startY; prevCmd = 'Z' }+ }+ }+ return path+}+private fun arcTo(path: Path, x0: Float, y0: Float, rxIn: Float, ryIn: Float, angle: Float, largeArcFlag: Int, sweepFlag: Int, x1: Float, y1: Float) {+ if (rxIn == 0f || ryIn == 0f) { path.lineTo(x1, y1); return }+ var rx = abs(rxIn).toDouble(); var ry = abs(ryIn).toDouble()+ val phi = Math.toRadians(angle.toDouble()); val cosPhi = cos(phi); val sinPhi = sin(phi)+ val dx2 = (x0 - x1) / 2.0; val dy2 = (y0 - y1) / 2.0+ val x1p = cosPhi * dx2 + sinPhi * dy2; val y1p = -sinPhi * dx2 + cosPhi * dy2+ var rxSq = rx * rx; var rySq = ry * ry; val x1pSq = x1p * x1p; val y1pSq = y1p * y1p+ var lambda = x1pSq / rxSq + y1pSq / rySq+ if (lambda > 1.0) { val s = sqrt(lambda); rx *= s; ry *= s; rxSq = rx * rx; rySq = ry * ry }+ val sign = if (largeArcFlag == sweepFlag) -1 else 1+ var num = rxSq * rySq - rxSq * y1pSq - rySq * x1pSq; if (num < 0) num = 0.0+ val denom = rxSq * y1pSq + rySq * x1pSq+ val factor = if (denom != 0.0) sign * sqrt(num / denom) else 0.0+ val cxp = factor * (rx * y1p / ry); val cyp = factor * (-ry * x1p / rx)+ val cx = cosPhi * cxp - sinPhi * cyp + (x0 + x1) / 2.0+ val cy = sinPhi * cxp + cosPhi * cyp + (y0 + y1) / 2.0+ val ux = (x1p - cxp) / rx; val uy = (y1p - cyp) / ry; val vx = (-x1p - cxp) / rx; val vy = (-y1p - cyp) / ry+ var theta1 = atan2(uy, ux); var deltaTheta = atan2(ux * vy - uy * vx, ux * vx + uy * vy)+ if (sweepFlag == 0 && deltaTheta > 0) deltaTheta -= 2 * Math.PI+ if (sweepFlag == 1 && deltaTheta < 0) deltaTheta += 2 * Math.PI+ val segs = ceil(abs(deltaTheta) / (Math.PI / 2)).toInt().coerceAtLeast(1)+ val delta = deltaTheta / segs; var curTheta = theta1+ for (i in 0 until segs) {+ val nextTheta = curTheta + delta+ val cosCur = cos(curTheta); val sinCur = sin(curTheta); val cosNext = cos(nextTheta); val sinNext = sin(nextTheta)+ val e2x = cx + rx * cosNext * cosPhi - ry * sinNext * sinPhi; val e2y = cy + rx * cosNext * sinPhi + ry * sinNext * cosPhi+ val dx1 = -rx * sinCur; val dy1 = ry * cosCur; val dx1r = dx1 * cosPhi - dy1 * sinPhi; val dy1r = dx1 * sinPhi + dy1 * cosPhi+ val dx2 = -rx * sinNext; val dy2 = ry * cosNext; val dx2r = dx2 * cosPhi - dy2 * sinPhi; val dy2r = dx2 * sinPhi + dy2 * cosPhi+ val k = (4.0 / 3.0) * tan(delta / 4.0)+ val e1x = cx + rx * cosCur * cosPhi - ry * sinCur * sinPhi; val e1y = cy + rx * cosCur * sinPhi + ry * sinCur * cosPhi+ val c1x = e1x + k * dx1r; val c1y = e1y + k * dy1r; val c2x = e2x - k * dx2r; val c2y = e2y - k * dy2r+ path.cubicTo(c1x.toFloat(), c1y.toFloat(), c2x.toFloat(), c2y.toFloat(), e2x.toFloat(), e2y.toFloat())+ curTheta = nextTheta+ }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex b863cd8c06..e8681d3cfd 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -22,7 +22,7 @@ dependencyResolutionManagement { mavenLocal() google() mavenCentral()- // JitPack kept only for Stockfish-Library (games:chess) — nanojson vendored to :third_party:nanojson+ // JitPack kept only for Stockfish-Library (games:chess) maven("https://jitpack.io") // sherpa-onnx (offline Piper TTS in :speech) isn't on Maven Central; the official // Apache-2.0 AAR is vendored into speech/libs by scripts/speech/fetch_sherpa_onnx.sh.@@ -31,7 +31,6 @@ dependencyResolutionManagement { } rootProject.name = "apps"-include(":third_party:nanojson") include(":library") include(":library:network") include(":library:biometric")
third_party/nanojson/LICENSE
diff --git a/third_party/nanojson/LICENSE b/third_party/nanojson/LICENSEdeleted file mode 100644index d645695673..0000000000--- a/third_party/nanojson/LICENSE+++ /dev/null@@ -1,202 +0,0 @@-- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright [yyyy] [name of copyright owner]-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.
third_party/nanojson/README.md
diff --git a/third_party/nanojson/README.md b/third_party/nanojson/README.mddeleted file mode 100644index 5f24bde161..0000000000--- a/third_party/nanojson/README.md+++ /dev/null@@ -1,22 +0,0 @@-# nanojson (vendored)--Vendored from https://github.com/TeamNewPipe/nanojson at pinned commit `e9d656ddb49a412a5a0a5d5ef20ca7ef09549996` (commit referenced in `gradle/libs.versions.toml` before migration).--## Why vendored-- Previously consumed via JitPack (`com.github.TeamNewPipe:nanojson`) which builds on-demand from GitHub commits — irreproducible risk, SPOF if JitPack sunsets.-- Critical to `youpipe` / `:youpipe:extractor` for YouTube JSON parsing.--## Contents-Files under `src/main/java/com/grack/nanojson/`:-- `JsonObject.java`-- `JsonArray.java`-- `JsonParser.java`-- `JsonWriter.java`-- `JsonBuilder.java`-- `JsonStringWriter.java`-- `JsonAppendableWriter.java`-- `JsonParserException.java`--## License-Apache License 2.0 — Copyright 2011 The nanojson Authors.-See `LICENSE` file. Original project license headers remain in source files.
third_party/nanojson/build.gradle.kts
diff --git a/third_party/nanojson/build.gradle.kts b/third_party/nanojson/build.gradle.ktsdeleted file mode 100644index d6ac503784..0000000000--- a/third_party/nanojson/build.gradle.kts+++ /dev/null@@ -1,16 +0,0 @@-import org.gradle.api.JavaVersion-import org.gradle.api.tasks.bundling.AbstractArchiveTask--plugins {- `java-library`-}--java {- sourceCompatibility = JavaVersion.VERSION_17- targetCompatibility = JavaVersion.VERSION_17-}--tasks.withType<AbstractArchiveTask>().configureEach {- isPreserveFileTimestamps = false- isReproducibleFileOrder = true-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonAppendableWriter.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonAppendableWriter.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonAppendableWriter.javadeleted file mode 100644index 63e864318a..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonAppendableWriter.java+++ /dev/null@@ -1,76 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.io.Flushable;-import java.io.IOException;-import java.io.OutputStream;--//@formatter:off-/**- * JSON writer that emits JSON to a {@link Appendable}.- * - * Create this class with {@link JsonWriter#on(Appendable)} or- * {@link JsonWriter#on(OutputStream)}.- * - * <pre>- * OutputStream out = ...;- * JsonWriter- * .indent(" ")- * .on(out)- * .object()- * .array("a")- * .value(1)- * .value(2)- * .end()- * .value("b", false)- * .value("c", true)- * .end()- * .done();- * </pre>- */-// @formatter:on-public final class JsonAppendableWriter extends- JsonWriterBase<JsonAppendableWriter> implements- JsonSink<JsonAppendableWriter> {- JsonAppendableWriter(Appendable appendable, String indent) {- super(appendable, indent);- }-- JsonAppendableWriter(OutputStream out, String indent) {- super(out, indent);- }-- /**- * Closes this JSON writer and flushes the underlying {@link Appendable} if- * it is also {@link Flushable}.- * - * @throws JsonWriterException- * if the underlying {@link Flushable} {@link Appendable} failed- * to flush.- */- public void done() throws JsonWriterException {- super.doneInternal();- try {- if (appendable instanceof Flushable)- ((Flushable) appendable).flush();- else if (out != null)- out.flush();- } catch (IOException e) {- throw new JsonWriterException(e);- }- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonArray.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonArray.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonArray.javadeleted file mode 100644index 58a8098c75..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonArray.java+++ /dev/null@@ -1,273 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.util.ArrayList;-import java.util.Arrays;-import java.util.Collection;-import java.util.stream.Stream;--/**- * Extends an {@link ArrayList} with helper methods to determine the underlying JSON type of the list element.- */-public class JsonArray extends ArrayList<Object> {- private static final long serialVersionUID = 1L;-- /**- * Creates an empty {@link JsonArray} with the default capacity.- */- public JsonArray() {- }-- /**- * Creates an empty {@link JsonArray} with the default initial capacity.- */- public JsonArray(int initialCapacity) {- super(initialCapacity);- }-- /**- * Creates an empty {@link JsonArray} from the given collection of objects.- */- public JsonArray(Collection<?> collection) {- super(collection);- }-- /**- * Creates a {@link JsonArray} from an array of contents.- */- public static JsonArray from(Object... contents) {- return new JsonArray(Arrays.asList(contents));- }-- /**- * Creates a {@link JsonBuilder} for a {@link JsonArray}.- */- public static JsonBuilder<JsonArray> builder() {- return new JsonBuilder<>(new JsonArray());- }- - /**- * Returns the underlying object at the given index, or null if it does not exist.- */- public Object get(int key) {- return key < size() ? super.get(key) : null;- }-- /**- * Returns the {@link JsonArray} at the given index, or an empty one if it does not exist or is the wrong type.- */- public JsonArray getArray(int key) {- return getArray(key, new JsonArray());- }-- /**- * Returns the {@link JsonArray} at the given index, or the default if it does not exist or is the wrong type.- */- public JsonArray getArray(int key, JsonArray default_) {- Object o = get(key);- if (o instanceof JsonArray)- return (JsonArray) o;- return default_;- }-- /**- * Returns the {@link Boolean} at the given index, or false if it does not exist or is the wrong type.- */- public boolean getBoolean(int key) {- return getBoolean(key, false);- }-- /**- * Returns the {@link Boolean} at the given index, or the default if it does not exist or is the wrong type.- */- public boolean getBoolean(int key, Boolean default_) {- Object o = get(key);- if (o instanceof Boolean)- return (Boolean) o;- return default_;- }-- /**- * Returns the {@link Double} at the given index, or 0.0 if it does not exist or is the wrong type.- */- public double getDouble(int key) {- return getDouble(key, 0);- }-- /**- * Returns the {@link Double} at the given index, or the default if it does not exist or is the wrong type.- */- public double getDouble(int key, double default_) {- Object o = get(key);- if (o instanceof Number)- return ((Number)o).doubleValue();- return default_;- }-- /**- * Returns the {@link Float} at the given index, or 0.0f if it does not exist or is the wrong type.- */- public float getFloat(int key) {- return getFloat(key, 0);- }-- /**- * Returns the {@link Float} at the given index, or the default if it does not exist or is the wrong type.- */- public float getFloat(int key, float default_) {- Object o = get(key);- if (o instanceof Number)- return ((Number)o).floatValue();- return default_;- }-- /**- * Returns the {@link Integer} at the given index, or 0 if it does not exist or is the wrong type.- */- public int getInt(int key) {- return getInt(key, 0);- }-- /**- * Returns the {@link Integer} at the given index, or the default if it does not exist or is the wrong type.- */- public int getInt(int key, int default_) {- Object o = get(key);- if (o instanceof Number)- return ((Number)o).intValue();- return default_;- }-- /**- * Returns the {@link Long} at the given index, or 0 if it does not exist or is the wrong type.- */- public long getLong(int key) {- return getLong(key, 0);- }-- /**- * Returns the {@link Long} at the given index, or the default if it does not exist or is the wrong type.- */- public long getLong(int key, long default_) {- Object o = get(key);- if (o instanceof Number)- return ((Number)o).longValue();- return default_;- }-- /**- * Returns the {@link Number} at the given index, or null if it does not exist or is the wrong type.- */- public Number getNumber(int key) {- return getNumber(key, null);- }-- /**- * Returns the {@link Number} at the given index, or the default if it does not exist or is the wrong type.- */- public Number getNumber(int key, Number default_) {- Object o = get(key);- if (o instanceof Number)- return (Number)o;- return default_;- }-- /**- * Returns the {@link JsonObject} at the given index, or an empty one if it does not exist or is the wrong type.- */- public JsonObject getObject(int key) {- return getObject(key, new JsonObject());- }-- /**- * Returns the {@link JsonObject} at the given index, or the default if it does not exist or is the wrong type.- */- public JsonObject getObject(int key, JsonObject default_) {- Object o = get(key);- if (o instanceof JsonObject)- return (JsonObject) o;- return default_;- }-- /**- * Returns the {@link String} at the given index, or null if it does not exist or is the wrong type.- */- public String getString(int key) {- return getString(key, null);- }-- /**- * Returns the {@link String} at the given index, or the default if it does not exist or is the wrong type.- */- public String getString(int key, String default_) {- Object o = get(key);- if (o instanceof String)- return (String) o;- return default_;- }-- /**- * Returns true if the array has an element at that index (even if that element is null).- */- public boolean has(int key) {- return key < size();- }-- /**- * Returns true if the array has a boolean element at that index.- */- public boolean isBoolean(int key) {- return get(key) instanceof Boolean;- }-- /**- * Returns true if the array has a null element at that index.- */- public boolean isNull(int key) {- return key < size() && get(key) == null;- }-- /**- * Returns true if the array has a number element at that index.- */- public boolean isNumber(int key) {- return get(key) instanceof Number;- }-- /**- * Returns true if the array has a string element at that index.- */- public boolean isString(int key) {- return get(key) instanceof String;- }-- /**- * Shortcut method to create a stream with only objects of these classes.- */- public <T> Stream<T> streamAs(Class<T> clazz) {- return stream()- .filter(clazz::isInstance)- .map(clazz::cast);- }-- /**- * Shortcut method to create a stream that only contains {@link JsonObject JsonObjects}.- */- public Stream<JsonObject> streamAsJsonObjects() {- return streamAs(JsonObject.class);- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonBuilder.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonBuilder.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonBuilder.javadeleted file mode 100644index 00bfaf2368..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonBuilder.java+++ /dev/null@@ -1,211 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.util.Collection;-import java.util.Map;-import java.util.Stack;--/**- * Builds a {@link JsonObject} or {@link JsonArray}.- * - * @param <T>- * The type of JSON object to build.- */-public final class JsonBuilder<T> implements JsonSink<JsonBuilder<T>> {- private Stack<Object> json = new Stack<>();- private T root;-- JsonBuilder(T root) {- this.root = root;- json.push(root);- }-- /**- * Completes this builder, closing any unclosed objects and returns the built object.- */- public T done() {- return root;- }- - @Override- public JsonBuilder<T> array(Collection<?> c) {- return value(c);- }-- @Override- public JsonBuilder<T> array(String key, Collection<?> c) {- return value(key, c);- }-- @Override- public JsonBuilder<T> object(Map<?, ?> map) {- return value(map);- }-- @Override- public JsonBuilder<T> object(String key, Map<?, ?> map) {- return value(key, map);- }-- @Override- public JsonBuilder<T> nul() {- return value((Object)null);- }-- @Override- public JsonBuilder<T> nul(String key) {- return value(key, (Object)null);- }-- @Override- public JsonBuilder<T> value(Object o) {- arr().add(o);- return this;- }-- @Override- public JsonBuilder<T> value(String key, Object o) {- obj().put(key, o);- return this;- }-- @Override- public JsonBuilder<T> value(String s) {- return value((Object)s);- }-- @Override- public JsonBuilder<T> value(int i) {- return value((Object)i);- }-- @Override- public JsonBuilder<T> value(long l) {- return value((Object)l);- }-- @Override- public JsonBuilder<T> value(boolean b) {- return value((Object)b);- }-- @Override- public JsonBuilder<T> value(double d) {- return value((Object)d);- }-- @Override- public JsonBuilder<T> value(float f) {- return value((Object)f);- }-- @Override- public JsonBuilder<T> value(Number n) {- return value((Object)n);- }-- @Override- public JsonBuilder<T> value(String key, String s) {- return value(key, (Object)s);- }-- @Override- public JsonBuilder<T> value(String key, int i) {- return value(key, (Object)i);- }-- @Override- public JsonBuilder<T> value(String key, long l) {- return value(key, (Object)l);- }-- @Override- public JsonBuilder<T> value(String key, boolean b) {- return value(key, (Object)b);- }-- @Override- public JsonBuilder<T> value(String key, double d) {- return value(key, (Object)d);- }-- @Override- public JsonBuilder<T> value(String key, float f) {- return value(key, (Object)f);- }-- @Override- public JsonBuilder<T> value(String key, Number n) {- return value(key, (Object)n);- }-- @Override- public JsonBuilder<T> array() {- JsonArray a = new JsonArray();- value(a);- json.push(a);- return this;- }-- @Override- public JsonBuilder<T> object() {- JsonObject o = new JsonObject();- value(o);- json.push(o);- return this;- }-- @Override- public JsonBuilder<T> array(String key) {- JsonArray a = new JsonArray();- value(key, a);- json.push(a);- return this;- }-- @Override- public JsonBuilder<T> object(String key) {- JsonObject o = new JsonObject();- value(key, o);- json.push(o);- return this;- }-- @Override- public JsonBuilder<T> end() {- if (json.size() == 1)- throw new JsonWriterException("Cannot end the root object or array");- json.pop();- return this;- }-- private JsonObject obj() {- try {- return (JsonObject)json.peek();- } catch (ClassCastException e) {- throw new JsonWriterException("Attempted to write a keyed value to a JsonArray");- }- }- - private JsonArray arr() {- try {- return (JsonArray)json.peek();- } catch (ClassCastException e) {- throw new JsonWriterException("Attempted to write a non-keyed value to a JsonObject");- }- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonLazyNumber.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonLazyNumber.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonLazyNumber.javadeleted file mode 100644index 080c6efa0f..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonLazyNumber.java+++ /dev/null@@ -1,59 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.math.BigDecimal;--/**- * Lazily-parsed number for performance.- */-@SuppressWarnings("serial")-class JsonLazyNumber extends Number {- private String value;- private boolean isDouble;-- JsonLazyNumber(String number, boolean isDoubleValue) {- this.value = number;- this.isDouble = isDoubleValue;- }-- @Override- public double doubleValue() {- return Double.parseDouble(value);- }-- @Override- public float floatValue() {- return Float.parseFloat(value);- }-- @Override- public int intValue() {- return isDouble ? (int)Double.parseDouble(value) : Integer.parseInt(value);- }-- @Override- public long longValue() {- return isDouble ? (long)Double.parseDouble(value) : Long.parseLong(value);- }-- /**- * Avoid serializing {@link JsonLazyNumber}.- */- private Object writeReplace() {- return new BigDecimal(value);- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonObject.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonObject.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonObject.javadeleted file mode 100644index 863728b63c..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonObject.java+++ /dev/null@@ -1,248 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.util.LinkedHashMap;-import java.util.Map;--/**- * Extends a {@link LinkedHashMap} with helper methods to determine the underlying JSON type of the map element.- */-public class JsonObject extends LinkedHashMap<String, Object> {- private static final long serialVersionUID = 1L;-- /**- * Creates an empty {@link JsonObject} with the default capacity.- */- public JsonObject() {- }-- /**- * Creates a {@link JsonObject} from an existing {@link Map}.- */- public JsonObject(Map<? extends String, ?> map) {- super(map);- }-- /**- * Creates a {@link JsonObject} with the given initial capacity.- */- public JsonObject(int initialCapacity) {- super(initialCapacity);- }-- /**- * Creates a {@link JsonObject} with the given initial capacity and load factor.- */- public JsonObject(int initialCapacity, float loadFactor) {- super(initialCapacity, loadFactor);- }-- /**- * Creates a {@link JsonBuilder} for a {@link JsonObject}.- */- public static JsonBuilder<JsonObject> builder() {- return new JsonBuilder<>(new JsonObject());- }-- /**- * Returns the {@link JsonArray} at the given key, or an empty one if it does not exist or is the wrong type.- */- public JsonArray getArray(String key) {- return getArray(key, new JsonArray());- }-- /**- * Returns the {@link JsonArray} at the given key, or the default if it does not exist or is the wrong type.- */- public JsonArray getArray(String key, JsonArray default_) {- Object o = get(key);- if (o instanceof JsonArray)- return (JsonArray) o;- return default_;- }-- /**- * Returns the {@link Boolean} at the given key, or false if it does not exist or is the wrong type.- */- public boolean getBoolean(String key) {- return getBoolean(key, false);- }-- /**- * Returns the {@link Boolean} at the given key, or the default if it does not exist or is the wrong type.- */- public boolean getBoolean(String key, Boolean default_) {- Object o = get(key);- if (o instanceof Boolean)- return (Boolean)o;- return default_;- }-- /**- * Returns the {@link Double} at the given key, or 0.0 if it does not exist or is the wrong type.- */- public double getDouble(String key) {- return getDouble(key, 0);- }-- /**- * Returns the {@link Double} at the given key, or the default if it does not exist or is the wrong type.- */- public double getDouble(String key, double default_) {- Object o = get(key);- if (o instanceof Number)- return ((Number)o).doubleValue();- return default_;- }-- /**- * Returns the {@link Float} at the given key, or 0.0f if it does not exist or is the wrong type.- */- public float getFloat(String key) {- return getFloat(key, 0);- }-- /**- * Returns the {@link Float} at the given key, or the default if it does not exist or is the wrong type.- */- public float getFloat(String key, float default_) {- Object o = get(key);- if (o instanceof Number)- return ((Number)o).floatValue();- return default_;- }-- /**- * Returns the {@link Integer} at the given key, or 0 if it does not exist or is the wrong type.- */- public int getInt(String key) {- return getInt(key, 0);- }-- /**- * Returns the {@link Integer} at the given key, or the default if it does not exist or is the wrong type.- */- public int getInt(String key, int default_) {- Object o = get(key);- if (o instanceof Number)- return ((Number)o).intValue();- return default_;- }-- /**- * Returns the {@link Long} at the given key, or 0 if it does not exist or is the wrong type.- */- public long getLong(String key) {- return getLong(key, 0);- }-- /**- * Returns the {@link Long} at the given key, or the default if it does not exist or is the wrong type.- */- public long getLong(String key, long default_) {- Object o = get(key);- if (o instanceof Number)- return ((Number)o).longValue();- return default_;- }-- /**- * Returns the {@link Number} at the given key, or null if it does not exist or is the wrong type.- */- public Number getNumber(String key) {- return getNumber(key, null);- }-- /**- * Returns the {@link Number} at the given key, or the default if it does not exist or is the wrong type.- */- public Number getNumber(String key, Number default_) {- Object o = get(key);- if (o instanceof Number)- return (Number)o;- return default_;- }-- /**- * Returns the {@link JsonObject} at the given key, or an empty one if it does not exist or is the wrong type.- */- public JsonObject getObject(String key) {- return getObject(key, new JsonObject());- }-- /**- * Returns the {@link JsonObject} at the given key, or the default if it does not exist or is the wrong type.- */- public JsonObject getObject(String key, JsonObject default_) {- Object o = get(key);- if (o instanceof JsonObject)- return (JsonObject) o;- return default_;- }-- /**- * Returns the {@link String} at the given key, or null if it does not exist or is the wrong type.- */- public String getString(String key) {- return getString(key, null);- }-- /**- * Returns the {@link String} at the given key, or the default if it does not exist or is the wrong type.- */- public String getString(String key, String default_) {- Object o = get(key);- if (o instanceof String)- return (String) o;- return default_;- }-- /**- * Returns true if the object has an element at that key (even if that element is null).- */- public boolean has(String key) {- return super.containsKey(key);- }-- /**- * Returns true if the object has a boolean element at that key.- */- public boolean isBoolean(String key) {- return get(key) instanceof Boolean;- }-- /**- * Returns true if the object has a null element at that key.- */- public boolean isNull(String key) {- return super.containsKey(key) && get(key) == null;- }-- /**- * Returns true if the object has a number element at that key.- */- public boolean isNumber(String key) {- return get(key) instanceof Number;- }-- /**- * Returns true if the object has a string element at that key.- */- public boolean isString(String key) {- return get(key) instanceof String;- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonParser.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonParser.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonParser.javadeleted file mode 100644index 3cbbfc0c91..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonParser.java+++ /dev/null@@ -1,281 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.io.IOException;-import java.io.InputStream;-import java.io.Reader;-import java.io.StringReader;-import java.math.BigInteger;-import java.net.URL;--/**- * Simple JSON parser.- * - * <pre>- * Object json = {@link JsonParser}.any().from("{\"a\":[true,false], \"b\":1}");- * Number json = ({@link Number}){@link JsonParser}.any().from("123.456e7");- * JsonObject json = {@link JsonParser}.object().from("{\"a\":[true,false], \"b\":1}");- * JsonArray json = {@link JsonParser}.array().from("[1, {\"a\":[true,false], \"b\":1}]");- * </pre>- */-public final class JsonParser {- private Object value;- private int token;-- private JsonTokener tokener;- private boolean lazyNumbers;-- /**- * Returns a type-safe parser context for a {@link JsonObject}, {@link JsonArray} or "any" type from which you can- * parse a {@link String} or a {@link Reader}.- *- * @param <T> The parsed type.- */- public static final class JsonParserContext<T> {- private final Class<T> clazz;- private boolean lazyNumbers;-- JsonParserContext(Class<T> clazz) {- this.clazz = clazz;- }-- /**- * Parses numbers lazily, allowing us to defer some of the cost of- * number construction until later.- */- public JsonParserContext<T> withLazyNumbers() {- lazyNumbers = true;- return this;- }-- /**- * Parses the current JSON type from a {@link String}.- */- public T from(String s) throws JsonParserException {- return new JsonParser(new JsonTokener(new StringReader(s)), lazyNumbers).parse(clazz);- }-- /**- * Parses the current` JSON type from a {@link Reader}.- */- public T from(Reader r) throws JsonParserException {- return new JsonParser(new JsonTokener(r), lazyNumbers).parse(clazz);- }-- /**- * Parses the current JSON type from a {@link URL}.- */- public T from(URL url) throws JsonParserException {- try {- InputStream stm = url.openStream();- try {- return from(stm);- } finally {- stm.close();- }- } catch (IOException e) {- throw new JsonParserException(e, "IOException opening URL", 1, 1, 0);- }- }-- /**- * Parses the current JSON type from a {@link InputStream}. Detects the encoding from the input stream.- */- public T from(InputStream stm) throws JsonParserException {- return new JsonParser(new JsonTokener(stm), lazyNumbers).parse(clazz);- }- }-- JsonParser(JsonTokener tokener, boolean lazyNumbers) throws JsonParserException {- this.tokener = tokener;- this.lazyNumbers = lazyNumbers;- }-- /**- * Parses a {@link JsonObject} from a source.- * - * <pre>- * JsonObject json = {@link JsonParser}.object().from("{\"a\":[true,false], \"b\":1}");- * </pre>- */- public static JsonParserContext<JsonObject> object() {- return new JsonParserContext<>(JsonObject.class);- }-- /**- * Parses a {@link JsonArray} from a source.- * - * <pre>- * JsonArray json = {@link JsonParser}.array().from("[1, {\"a\":[true,false], \"b\":1}]");- * </pre>- */- public static JsonParserContext<JsonArray> array() {- return new JsonParserContext<>(JsonArray.class);- }-- /**- * Parses any object from a source. For any valid JSON, returns either a null (for the JSON string 'null'), a- * {@link String}, a {@link Number}, a {@link Boolean}, a {@link JsonObject} or a {@link JsonArray}.- * - * <pre>- * Object json = {@link JsonParser}.any().from("{\"a\":[true,false], \"b\":1}");- * Number json = ({@link Number}){@link JsonParser}.any().from("123.456e7");- * </pre>- */- public static JsonParserContext<Object> any() {- return new JsonParserContext<>(Object.class);- }-- /**- * Parse a single JSON value from the string, expecting an EOF at the end.- */- <T> T parse(Class<T> clazz) throws JsonParserException {- advanceToken(false, false);- Object parsed = currentValue();- if (advanceToken(false, false) != JsonTokener.TOKEN_EOF)- throw tokener.createParseException(null, "Expected end of input, got " + token, true);- if (clazz != Object.class && (parsed == null || !clazz.isAssignableFrom(parsed.getClass())))- throw tokener.createParseException(null,- "JSON did not contain the correct type, expected " + clazz.getSimpleName() + ".", - true);- return clazz.cast(parsed);- }-- /**- * Starts parsing a JSON value at the current token position.- */- private Object currentValue() throws JsonParserException {- // Only a value start token should appear when we're in the context of parsing a JSON value- if (token >= JsonTokener.TOKEN_VALUE_MIN)- return value;- throw tokener.createParseException(null, "Expected JSON value, got " + token, true);- }-- /**- * Consumes a token, first eating up any whitespace ahead of it. Note that number tokens are not necessarily valid- * numbers.- */- private int advanceToken(boolean allowSemiString, boolean old) throws JsonParserException {- if (old) tokener.index--;- token = tokener.advanceToToken(allowSemiString);- switch (token) {- case JsonTokener.TOKEN_ARRAY_START: // Inlined function to avoid additional stack- JsonArray list = new JsonArray();- if (advanceToken(false, false) != JsonTokener.TOKEN_ARRAY_END)- while (true) {- list.add(currentValue());- if (token == JsonTokener.TOKEN_SEMI_STRING)- throw tokener.createParseException(null, "Semi-string is not allowed in array", true);- if (advanceToken(false, false) == JsonTokener.TOKEN_ARRAY_END)- break;- if (token != JsonTokener.TOKEN_COMMA)- throw tokener.createParseException(null,- "Expected a comma or end of the array instead of " + token, true);- if (advanceToken(false, false) == JsonTokener.TOKEN_ARRAY_END)- throw tokener.createParseException(null, "Trailing comma found in array", true);- }- value = list;- return token = JsonTokener.TOKEN_ARRAY_START;- case JsonTokener.TOKEN_OBJECT_START: // Inlined function to avoid additional stack- JsonObject map = new JsonObject();- if (advanceToken(true, false) != JsonTokener.TOKEN_OBJECT_END)- while (true) {- switch (token) {- case JsonTokener.TOKEN_NULL:- case JsonTokener.TOKEN_TRUE:- case JsonTokener.TOKEN_FALSE:- value = value.toString();- break;- case JsonTokener.TOKEN_STRING:- case JsonTokener.TOKEN_SEMI_STRING:- break;- default:- throw tokener.createParseException(null, "Expected STRING, got " + token, true);- }- String key = (String)value;- if (token == JsonTokener.TOKEN_SEMI_STRING) {- if (advanceToken(false, true) != JsonTokener.TOKEN_COLON)- throw tokener.createParseException(null, "Expected COLON, got " + token, true);- } else if (advanceToken(false, false) != JsonTokener.TOKEN_COLON)- throw tokener.createParseException(null, "Expected COLON, got " + token, true);- advanceToken(false, false);- map.put(key, currentValue());- if (advanceToken(false, false) == JsonTokener.TOKEN_OBJECT_END)- break;- if (token != JsonTokener.TOKEN_COMMA)- throw tokener.createParseException(null,- "Expected a comma or end of the object instead of " + token, true);- if (advanceToken(true, false) == JsonTokener.TOKEN_OBJECT_END)- throw tokener.createParseException(null, "Trailing object found in array", true);- }- value = map;- return token = JsonTokener.TOKEN_OBJECT_START;- case JsonTokener.TOKEN_TRUE:- value = Boolean.TRUE;- break;- case JsonTokener.TOKEN_FALSE:- value = Boolean.FALSE;- break;- case JsonTokener.TOKEN_NULL:- value = null;- break;- case JsonTokener.TOKEN_STRING:- case JsonTokener.TOKEN_SEMI_STRING:- value = tokener.reusableBuffer.toString();- break;- case JsonTokener.TOKEN_NUMBER:- if (lazyNumbers) {- value = new JsonLazyNumber(tokener.reusableBuffer.toString(), tokener.isDouble);- } else {- value = parseNumber();- }- break;- default:- }-- return token;- }-- private Number parseNumber() throws JsonParserException {- String number = tokener.reusableBuffer.toString();-- try {- if (tokener.isDouble)- return Double.parseDouble(number);-- // Quick parse for single-digits- if (number.length() == 1) {- return number.charAt(0) - '0';- } else if (number.length() == 2 && number.charAt(0) == '-') {- return '0' - number.charAt(1);- }-- // HACK: Attempt to parse using the approximate best type for this- boolean firstMinus = number.charAt(0) == '-';- int length = firstMinus ? number.length() - 1 : number.length();- // CHECKSTYLE_OFF: MagicNumber- if (length < 10 || (length == 10 && number.charAt(firstMinus ? 1 : 0) < '2')) // 2 147 483 647- return Integer.parseInt(number);- if (length < 19 || (length == 19 && number.charAt(firstMinus ? 1 : 0) < '9')) // 9 223 372 036 854 775 807- return Long.parseLong(number);- // CHECKSTYLE_ON: MagicNumber- return new BigInteger(number);- } catch (NumberFormatException e) {- throw tokener.createParseException(e, "Malformed number: " + number, true);- }- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonParserException.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonParserException.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonParserException.javadeleted file mode 100644index 8428472e59..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonParserException.java+++ /dev/null@@ -1,54 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--/**- * Thrown when the {@link JsonParser} encounters malformed JSON.- */-public class JsonParserException extends Exception {- private static final long serialVersionUID = 1L;- private final int linePos;- private final int charPos;- private final int charOffset;-- JsonParserException(Exception e, String message, int linePos, int charPos, int charOffset) {- super(message, e);- this.linePos = linePos;- this.charPos = charPos;- this.charOffset = charOffset;- }-- /**- * Gets the 1-based line position of the error.- */- public int getLinePosition() {- return linePos;- }-- /**- * Gets the 1-based character position of the error.- */- public int getCharPosition() {- return charPos;- }- - /**- * Gets the 0-based character offset of the error from the beginning of the string.- */- public int getCharOffset() {- return charOffset;- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonReader.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonReader.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonReader.javadeleted file mode 100644index b9ea2cbe87..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonReader.java+++ /dev/null@@ -1,315 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.io.InputStream;-import java.io.StringReader;-import java.util.Arrays;-import java.util.BitSet;--/**- * Streaming reader for JSON documents.- */-public final class JsonReader {- private JsonTokener tokener;- private int token;- private BitSet states = new BitSet();- private int stateIndex = 0;- private boolean inObject;- private boolean first = true;- private StringBuilder key = new StringBuilder();-- /**- * The type of value that the {@link JsonReader} is positioned over.- */- public enum Type {- /**- * An object.- */- OBJECT,- /**- * An array.- */- ARRAY,- /**- * A string.- */- STRING,- /**- * A number.- */- NUMBER,- /**- * A boolean value (true or false).- */- BOOLEAN,- /**- * A null value.- */- NULL,- };-- /**- * Create a {@link JsonReader} from an {@link InputStream}.- */- public static JsonReader from(InputStream in) throws JsonParserException {- return new JsonReader(new JsonTokener(in));- }-- /**- * Create a {@link JsonReader} from a {@link String}.- */- public static JsonReader from(String s) throws JsonParserException {- return new JsonReader(new JsonTokener(new StringReader(s)));- }-- /**- * Internal constructor.- */- JsonReader(JsonTokener tokener) throws JsonParserException {- this.tokener = tokener;- token = tokener.advanceToToken(false);- }-- /**- * Returns to the array or object structure above the current one, and- * advances to the next key or value.- */- public boolean pop() throws JsonParserException {- // CHECKSTYLE_OFF: EmptyStatement- while (!next());- // CHECKSTYLE_ON: EmptyStatement- first = false;- inObject = states.get(--stateIndex);- return token != JsonTokener.TOKEN_EOF;- }-- /**- * Returns the current type of the value.- */- public Type current() throws JsonParserException {- switch (token) {- case JsonTokener.TOKEN_TRUE:- case JsonTokener.TOKEN_FALSE:- return Type.BOOLEAN;- case JsonTokener.TOKEN_NULL:- return Type.NULL;- case JsonTokener.TOKEN_NUMBER:- return Type.NUMBER;- case JsonTokener.TOKEN_STRING:- return Type.STRING;- case JsonTokener.TOKEN_OBJECT_START:- return Type.OBJECT;- case JsonTokener.TOKEN_ARRAY_START:- return Type.ARRAY;- default: - throw createTokenMismatchException(JsonTokener.TOKEN_NULL, JsonTokener.TOKEN_TRUE, - JsonTokener.TOKEN_FALSE, JsonTokener.TOKEN_NUMBER, JsonTokener.TOKEN_STRING,- JsonTokener.TOKEN_OBJECT_START, JsonTokener.TOKEN_ARRAY_START);- }- }-- /**- * Starts reading an object at the current value.- */- public void object() throws JsonParserException {- if (token != JsonTokener.TOKEN_OBJECT_START)- throw createTokenMismatchException(JsonTokener.TOKEN_OBJECT_START);- states.set(stateIndex++, inObject);- inObject = true;- first = true;- }-- /**- * Reads the key for the object at the current value. Does not advance to the next value.- */- public String key() throws JsonParserException {- if (!inObject)- throw tokener.createParseException(null, "Not reading an object", true);- return key.toString();- }-- /**- * Starts reading an array at the current value.- */- public void array() throws JsonParserException {- if (token != JsonTokener.TOKEN_ARRAY_START)- throw createTokenMismatchException(JsonTokener.TOKEN_ARRAY_START);- states.set(stateIndex++, inObject);- inObject = false;- first = true;- }-- /**- * Returns the current value.- */- public Object value() throws JsonParserException {- switch (token) {- case JsonTokener.TOKEN_TRUE:- return true;- case JsonTokener.TOKEN_FALSE:- return false;- case JsonTokener.TOKEN_NULL:- return null;- case JsonTokener.TOKEN_NUMBER:- return number();- case JsonTokener.TOKEN_STRING:- return string();- default: - throw createTokenMismatchException(JsonTokener.TOKEN_NULL, JsonTokener.TOKEN_TRUE, JsonTokener.TOKEN_FALSE,- JsonTokener.TOKEN_NUMBER, JsonTokener.TOKEN_STRING);- }- }-- /**- * Parses the current value as a null.- */- public void nul() throws JsonParserException {- if (token != JsonTokener.TOKEN_NULL)- throw createTokenMismatchException(JsonTokener.TOKEN_NULL);- }-- /**- * Parses the current value as a string.- */- public String string() throws JsonParserException {- if (token == JsonTokener.TOKEN_NULL)- return null;- if (token != JsonTokener.TOKEN_STRING)- throw createTokenMismatchException(JsonTokener.TOKEN_NULL, JsonTokener.TOKEN_STRING);- return tokener.reusableBuffer.toString();- }-- /**- * Parses the current value as a boolean.- */- public boolean bool() throws JsonParserException {- if (token == JsonTokener.TOKEN_TRUE)- return true;- else if (token == JsonTokener.TOKEN_FALSE)- return false;- else- throw createTokenMismatchException(JsonTokener.TOKEN_TRUE, JsonTokener.TOKEN_FALSE);- }-- /**- * Parses the current value as a {@link Number}.- */- public Number number() throws JsonParserException {- if (token == JsonTokener.TOKEN_NULL)- return null;- return new JsonLazyNumber(tokener.reusableBuffer.toString(), tokener.isDouble);- }-- /**- * Parses the current value as a long.- */- public long longVal() throws JsonParserException {- String s = tokener.reusableBuffer.toString();- return tokener.isDouble ? (long)Double.parseDouble(s) : Long.parseLong(s);- }-- /**- * Parses the current value as an integer.- */- public int intVal() throws JsonParserException {- String s = tokener.reusableBuffer.toString();- return tokener.isDouble ? (int)Double.parseDouble(s) : Integer.parseInt(s);- }-- /**- * Parses the current value as a float.- */- public float floatVal() throws JsonParserException {- String s = tokener.reusableBuffer.toString();- return Float.parseFloat(s);- }-- /**- * Parses the current value as a double.- */- public double doubleVal() throws JsonParserException {- String s = tokener.reusableBuffer.toString();- return Double.parseDouble(s);- }-- /**- * Advance to the next value in this array or object. If no values remain,- * return to the parent array or object.- * - * @return true if we still have values to read in this array or object,- * false if we have completed this object (and implicitly moved back- * to the parent array or object)- */- public boolean next() throws JsonParserException {- if (stateIndex == 0) {- throw tokener.createParseException(null, "Unabled to call next() at the root", true); - }- - token = tokener.advanceToToken(false);-- if (inObject) {- if (token == JsonTokener.TOKEN_OBJECT_END) {- inObject = states.get(--stateIndex);- first = false;- return false;- }- - if (!first) {- if (token != JsonTokener.TOKEN_COMMA)- throw createTokenMismatchException(JsonTokener.TOKEN_COMMA, JsonTokener.TOKEN_OBJECT_END);- token = tokener.advanceToToken(false);- }-- if (token != JsonTokener.TOKEN_STRING)- throw createTokenMismatchException(JsonTokener.TOKEN_STRING);- key.setLength(0);- key.append(tokener.reusableBuffer); // reduce string garbage - if ((token = tokener.advanceToToken(false)) != JsonTokener.TOKEN_COLON)- throw createTokenMismatchException(JsonTokener.TOKEN_COLON);- token = tokener.advanceToToken(false);- } else {- if (token == JsonTokener.TOKEN_ARRAY_END) {- inObject = states.get(--stateIndex);- first = false;- return false;- }- if (!first) {- if (token != JsonTokener.TOKEN_COMMA)- throw createTokenMismatchException(JsonTokener.TOKEN_COMMA, JsonTokener.TOKEN_ARRAY_END);- token = tokener.advanceToToken(false);- }- }-- if (token != JsonTokener.TOKEN_NULL && token != JsonTokener.TOKEN_STRING- && token != JsonTokener.TOKEN_NUMBER && token != JsonTokener.TOKEN_TRUE- && token != JsonTokener.TOKEN_FALSE && token != JsonTokener.TOKEN_OBJECT_START- && token != JsonTokener.TOKEN_ARRAY_START)- throw createTokenMismatchException(JsonTokener.TOKEN_NULL, JsonTokener.TOKEN_STRING,- JsonTokener.TOKEN_NUMBER, JsonTokener.TOKEN_TRUE, JsonTokener.TOKEN_FALSE,- JsonTokener.TOKEN_OBJECT_START, JsonTokener.TOKEN_ARRAY_START);-- first = false;- - return true;- }- - private JsonParserException createTokenMismatchException(int... t) {- return tokener.createParseException(null, "token mismatch (expected " + Arrays.toString(t)- + ", was " + token + ")",- true);- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonSink.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonSink.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonSink.javadeleted file mode 100644index 73d8f02ec9..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonSink.java+++ /dev/null@@ -1,162 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.util.Collection;-import java.util.Map;--/**- * Common interface for {@link JsonAppendableWriter}, {@link JsonStringWriter} and {@link JsonBuilder}.- * - * @param <SELF>- * A subclass of {@link JsonSink}.- */-public interface JsonSink<SELF extends JsonSink<SELF>> {- /**- * Emits the start of an array.- */- SELF array(Collection<?> c);-- /**- * Emits the start of an array with a key.- */- SELF array(String key, Collection<?> c);- - /**- * Emits the start of an object.- */- SELF object(Map<?, ?> map);-- /**- * Emits the start of an object with a key.- */- SELF object(String key, Map<?, ?> map);-- /**- * Emits a 'null' token.- */- SELF nul();-- /**- * Emits a 'null' token with a key.- */- SELF nul(String key);-- /**- * Emits an object if it is a JSON-compatible type, otherwise throws an exception.- */- SELF value(Object o);-- /**- * Emits an object with a key if it is a JSON-compatible type, otherwise throws an exception.- */- SELF value(String key, Object o);-- /**- * Emits a string value (or null).- */- SELF value(String s);-- /**- * Emits an integer value.- */- SELF value(int i);-- /**- * Emits a long value.- */- SELF value(long l);-- /**- * Emits a boolean value.- */- SELF value(boolean b);-- /**- * Emits a double value.- */- SELF value(double d);-- /**- * Emits a float value.- */- SELF value(float f);-- /**- * Emits a {@link Number} value.- */- SELF value(Number n);-- /**- * Emits a string value (or null) with a key.- */- SELF value(String key, String s);-- /**- * Emits an integer value with a key.- */- SELF value(String key, int i);- - /**- * Emits a long value with a key.- */- SELF value(String key, long l);-- /**- * Emits a boolean value with a key.- */- SELF value(String key, boolean b);-- /**- * Emits a double value with a key.- */- SELF value(String key, double d);-- /**- * Emits a float value with a key.- */- SELF value(String key, float f);-- /**- * Emits a {@link Number} value with a key.- */- SELF value(String key, Number n);-- /**- * Starts an array.- */- SELF array();-- /**- * Starts an object.- */- SELF object();-- /**- * Starts an array within an object, prefixed with a key.- */- SELF array(String key);-- /**- * Starts an object within an object, prefixed with a key.- */- SELF object(String key);-- /**- * Ends the current array or object.- */- SELF end();-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonStringWriter.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonStringWriter.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonStringWriter.javadeleted file mode 100644index 3510ca8f53..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonStringWriter.java+++ /dev/null@@ -1,52 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--//@formatter:off-/**- * JSON writer that emits JSON to a {@link String}.- * - * Create this class using {@link JsonWriter#string()}.- * - * <pre>- * String json = JsonEmitter- * .indent(" ")- * .string()- * .object()- * .array("a")- * .value(1)- * .value(2)- * .end()- * .value("b", false)- * .value("c", true)- * .end()- * .done();- * </pre>- */-//@formatter:on-public final class JsonStringWriter extends JsonWriterBase<JsonStringWriter> {- JsonStringWriter(String indent) {- super(new StringBuilder(), indent);- }-- /**- * Completes this JSON writing session and returns the internal representation as a {@link String}.- */- public String done() {- super.doneInternal();- return appendable.toString();- }-}
third_party/nanojson/src/main/java/com/grack/nanojson/JsonTokener.java
diff --git a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonTokener.java b/third_party/nanojson/src/main/java/com/grack/nanojson/JsonTokener.javadeleted file mode 100644index d7a45a20ef..0000000000--- a/third_party/nanojson/src/main/java/com/grack/nanojson/JsonTokener.java+++ /dev/null@@ -1,941 +0,0 @@-/*- * Copyright 2011 The nanojson Authors- *- * Licensed under the Apache License, Version 2.0 (the "License"); you may not- * use this file except in compliance with the License. You may obtain a copy of- * the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the- * License for the specific language governing permissions and limitations under- * the License.- */-package com.grack.nanojson;--import java.io.BufferedInputStream;-import java.io.ByteArrayInputStream;-import java.io.IOException;-import java.io.InputStream;-import java.io.InputStreamReader;-import java.io.Reader;-import java.nio.charset.Charset;-import java.nio.charset.StandardCharsets;--/**- * Internal class for tokenizing JSON. Used by both {@link JsonParser} and {@link JsonReader}.- */-final class JsonTokener {- // Used by tests- static final int BUFFER_SIZE = 32 * 1024;-- static final int BUFFER_ROOM = 256;- static final int MAX_ESCAPE = 5; // uXXXX (don't need the leading slash)-- private int linePos = 1, rowPos, charOffset, utf8adjust;- private int tokenCharPos, tokenCharOffset;-- private boolean eof;- protected int index;- private final Reader reader;- private final char[] buffer = new char[BUFFER_SIZE];- private int bufferLength;-- private final boolean utf8;-- protected StringBuilder reusableBuffer = new StringBuilder();- protected boolean isDouble;-- static final char[] TRUE = { 'r', 'u', 'e' };- static final char[] FALSE = { 'a', 'l', 's', 'e' };- static final char[] NULL = { 'u', 'l', 'l' };-- static final int TOKEN_EOF = 0;- static final int TOKEN_COMMA = 1;- static final int TOKEN_COLON = 2;- static final int TOKEN_OBJECT_END = 3;- static final int TOKEN_ARRAY_END = 4;- static final int TOKEN_NULL = 5;- static final int TOKEN_TRUE = 6;- static final int TOKEN_FALSE = 7;- static final int TOKEN_STRING = 8;- static final int TOKEN_NUMBER = 9;- static final int TOKEN_OBJECT_START = 10;- static final int TOKEN_ARRAY_START = 11;- static final int TOKEN_SEMI_STRING = 12;- static final int TOKEN_VALUE_MIN = TOKEN_NULL;-- /**- * A {@link Reader} that reads a UTF8 stream without decoding it for performance.- */- private static final class PseudoUtf8Reader extends Reader {- private final InputStream buffered;- private byte[] buf = new byte[BUFFER_SIZE];-- PseudoUtf8Reader(InputStream buffered) {- this.buffered = buffered;- }-- @Override- public int read(char[] cbuf, int off, int len) throws IOException {- int r = buffered.read(buf, off, len);- for (int i = off; i < off + r; i++)- cbuf[i] = (char)buf[i];- return r;- }-- @Override- public void close() throws IOException {- }- }- - JsonTokener(Reader reader) throws JsonParserException {- this.reader = reader;- this.utf8 = false;- init();- }- - JsonTokener(InputStream stm) throws JsonParserException {- final InputStream buffered = (stm instanceof BufferedInputStream || stm instanceof ByteArrayInputStream) - ? stm- : new BufferedInputStream(stm);- buffered.mark(4);-- try {- Charset charset;- int[] sig = new int[] { buffered.read(), buffered.read(), buffered.read(), buffered.read() };- // Encoding detection based on http://www.ietf.org/rfc/rfc4627.txt- if (sig[0] == 0xEF && sig[1] == 0xBB && sig[2] == 0xBF) {- buffered.reset();- buffered.read();- buffered.read();- buffered.read();- this.reader = new PseudoUtf8Reader(buffered);- this.utf8 = true;- init();- return;- } else if (sig[0] == 0x00 && sig[1] == 0x00 && sig[2] == 0xFE && sig[3] == 0xFF) {- charset = Charset.forName("UTF-32BE");- } else if (sig[0] == 0xFF && sig[1] == 0xFE && sig[2] == 0x00 && sig[3] == 0x00) {- charset = Charset.forName("UTF-32LE");- } else if (sig[0] == 0xFE && sig[1] == 0xFF) {- charset = StandardCharsets.UTF_16BE;- buffered.reset();- buffered.read();- buffered.read();- } else if (sig[0] == 0xFF && sig[1] == 0xFE) {- charset = StandardCharsets.UTF_16LE;- buffered.reset();- buffered.read();- buffered.read();- } else if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0 && sig[3] != 0) {- charset = Charset.forName("UTF-32BE");- buffered.reset();- } else if (sig[0] != 0 && sig[1] == 0 && sig[2] == 0 && sig[3] == 0) {- charset = Charset.forName("UTF-32LE");- buffered.reset();- } else if (sig[0] == 0 && sig[1] != 0 && sig[2] == 0 && sig[3] != 0) {- charset = StandardCharsets.UTF_16BE;- buffered.reset();- } else if (sig[0] != 0 && sig[1] == 0 && sig[2] != 0 && sig[3] == 0) {- charset = StandardCharsets.UTF_16LE;- buffered.reset();- } else {- buffered.reset();- this.reader = new PseudoUtf8Reader(buffered);- this.utf8 = true;- init();- return;- }- this.reader = new InputStreamReader(buffered, charset);- this.utf8 = false;- init();- } catch (IOException e) {- throw new JsonParserException(e, "IOException while detecting charset", 1, 1, 0);- }- }-- private void init() throws JsonParserException {- eof = refillBuffer();- consumeWhitespace();- }-- /**- * Expects a given string at the current position.- */- void consumeKeyword(char first, char[] expected) throws JsonParserException {- if (ensureBuffer(expected.length) < expected.length) {- throw createHelpfulException(first, expected, 0);- }-- for (int i = 0; i < expected.length; i++)- if (buffer[index++] != expected[i])- throw createHelpfulException(first, expected, i);-- fixupAfterRawBufferRead();-- // The token shouldn't end with something other than an ASCII letter- switch (peekChar()) {- case ',':- case ':':- case '{':- case '}':- case '[':- case ']':- case ' ':- case '\n':- case '\r':- case '\t':- break;- default:- throw createHelpfulException(first, expected, expected.length);- }- }-- /**- * Steps through to the end of the current number token (a non-digit token).- */- void consumeTokenNumber(char savedChar) throws JsonParserException {- reusableBuffer.setLength(0);- reusableBuffer.append(savedChar);- isDouble = false;-- // The JSON spec is way stricter about number formats than- // Double.parseDouble(). This is a hand-rolled pseudo-parser that- // verifies numbers we read.- int state;- if (savedChar == '-') {- state = 1;- } else if (savedChar == '0') {- state = 3;- } else {- state = 2;- }- - outer:- while (true) {- int n = ensureBuffer(BUFFER_ROOM);- if (n == 0)- break outer;-- for (int i = 0; i < n; i++) {- char nc = buffer[index];- if (!isDigitCharacter(nc))- break outer;-- int ns = -1;- sw:- switch (state) {- case 1: // start leading negative- if (nc == '0') {- ns = 3; break sw;- }- if (nc > '0' && nc <= '9') {- ns = 2; break sw;- }- break;- case 2: // no leading zero- case 3: // leading zero- if ((nc >= '0' && nc <= '9') && state == 2) {- ns = 2; break sw;- }- if (nc == '.') {- isDouble = true;- ns = 4; break sw;- }- if (nc == 'e' || nc == 'E') {- isDouble = true;- ns = 6; break sw;- }- break;- case 4: // after period- case 5: // after period, one digit read- if (nc >= '0' && nc <= '9') {- ns = 5; break sw;- }- if ((nc == 'e' || nc == 'E') && state == 5) {- isDouble = true;- ns = 6; break sw;- }- break;- case 6: // after exponent- case 7: // after exponent and sign- if (nc == '+' || nc == '-' && state == 6) {- ns = 7; break sw;- }- if (nc >= '0' && nc <= '9') {- ns = 8; break sw;- }- break;- case 8: // after digits- if (nc >= '0' && nc <= '9') {- ns = 8; break sw;- }- break;- default:- assert false : "Impossible"; // will throw malformed number- }- reusableBuffer.append(nc);- index++;- if (ns == -1)- throw createParseException(null, "Malformed number: " + reusableBuffer, true);- state = ns;- }- }- - if (state != 2 && state != 3 && state != 5 && state != 8)- throw createParseException(null, "Malformed number: " + reusableBuffer, true);- - // Special case for -0- if (state == 3 && savedChar == '-')- isDouble = true;- - fixupAfterRawBufferRead();- }-- /**- * Steps through to the end of the current string token (the unescaped double quote).- */- void consumeTokenString(int cc) throws JsonParserException {- reusableBuffer.setLength(0);- - // Assume no escapes or UTF-8 in the string to start (fast path)- start:- while (true) {- int n = ensureBuffer(BUFFER_ROOM);- if (n == 0)- throw createParseException(null, "String was not terminated before end of input", true);- - for (int i = 0; i < n; i++) {- char c = stringChar();- if (c == cc) {- // Use the index before we fixup- reusableBuffer.append(buffer, index - i - 1, i);- fixupAfterRawBufferRead();- return;- }- if (c == '\\' || (utf8 && (c & 0x80) != 0)) {- reusableBuffer.append(buffer, index - i - 1, i);- index--;- break start;- }- }- - reusableBuffer.append(buffer, index - n, n);- }- - outer:- while (true) {- int n = ensureBuffer(BUFFER_ROOM);- if (n == 0)- throw createParseException(null, "String was not terminated before end of input", true);- - int end = index + n;- while (index < end) {- char c = stringChar();- - if (utf8 && (c & 0x80) != 0) {- // If it's a UTF-8 codepoint, we know it won't have special meaning- consumeTokenStringUtf8Char(c);- continue outer;- }- - switch (c) {- case '"':- case '\'':- if (c == cc) {- fixupAfterRawBufferRead();- return;- } else {- reusableBuffer.append(c);- break;- }- case '\\':- // Ensure that we have at least MAX_ESCAPE here in the buffer- if (end - index < MAX_ESCAPE) {- // Re-adjust the buffer end, unlikely path- n = ensureBuffer(MAX_ESCAPE);- end = index + n;- // Make sure that there's enough chars for a \\uXXXX escape- if (buffer[index] == 'u' && n < MAX_ESCAPE) {- index = bufferLength; // Reset index to last valid location- throw createParseException(null, "EOF encountered in the middle of a string escape", false);- }- }- char escape = buffer[index++];- switch (escape) {- case 'b':- reusableBuffer.append('\b');- break;- case 'f':- reusableBuffer.append('\f');- break;- case 'n':- reusableBuffer.append('\n');- break;- case 'r':- reusableBuffer.append('\r');- break;- case 't':- reusableBuffer.append('\t');- break;- case '"':- case '\'':- case '/':- case '\\':- reusableBuffer.append(escape);- break;- case 'u':- int escaped = 0;- - for (int j = 0; j < 4; j++) {- escaped <<= 4;- int digit = buffer[index++];- if (digit >= '0' && digit <= '9') {- escaped |= (digit - '0');- } else if (digit >= 'A' && digit <= 'F') {- escaped |= (digit - 'A') + 10;- } else if (digit >= 'a' && digit <= 'f') {- escaped |= (digit - 'a') + 10;- } else {- throw createParseException(null, "Expected unicode hex escape character: "- + (char)digit + " (" + digit + ")", false);- }- }- - reusableBuffer.append((char)escaped);- break;- default:- throw createParseException(null, "Invalid escape: \\" + escape, false);- }- break;- default:- reusableBuffer.append(c);- }- }- - if (index > bufferLength) {- index = bufferLength; // Reset index to last valid location- throw createParseException(null, "EOF encountered in the middle of a string escape", false);- }- }- }-- void consumeTokenSemiString() throws JsonParserException {- reusableBuffer.setLength(0);-- start:- while (true) {- int n = ensureBuffer(BUFFER_ROOM);- if (n == 0)- throw createParseException(null, "String was not terminated before end of input", true);-- for (int i = 0; i < n; i++) {- char c = stringChar();- if (isWhitespace(c) || c == ':') {- // Use the index before we fixup- reusableBuffer.append(buffer, index - i - 1, i);- fixupAfterRawBufferRead();- return;- }- if (c == '\\' || (utf8 && (c & 0x80) != 0)) {- reusableBuffer.append(buffer, index - i - 1, i);- index--;- break start;- }- if (c == '[' || c == ']' || c == '{' || c == '}' || c == ',') {- throw createParseException(null, "Invalid character in semi-string: " + c, false);- }- }-- reusableBuffer.append(buffer, index - n, n);- }-- outer:- while (true) {- int n = ensureBuffer(BUFFER_ROOM);- if (n == 0)- throw createParseException(null, "String was not terminated before end of input", true);-- int end = index + n;- while (index < end) {- char c = stringChar();-- if (utf8 && (c & 0x80) != 0) {- // If it's a UTF-8 codepoint, we know it won't have special meaning- consumeTokenStringUtf8Char(c);- continue outer;- }-- switch (c) {- case ' ':- case '\n':- case '\r':- case '\t':- case ':':- fixupAfterRawBufferRead();- return;- case '[':- case ']':- case '{':- case '}':- case ',':- throw createParseException(null, "Invalid character in semi-string: " + c, false);- case '\\':- // Ensure that we have at least MAX_ESCAPE here in the buffer- if (end - index < MAX_ESCAPE) {- // Re-adjust the buffer end, unlikely path- n = ensureBuffer(MAX_ESCAPE);- end = index + n;- // Make sure that there's enough chars for a \\uXXXX escape- if (buffer[index] == 'u' && n < MAX_ESCAPE) {- index = bufferLength; // Reset index to last valid location- throw createParseException(null, "EOF encountered in the middle of a string escape", false);- }- }- char escape = buffer[index++];- switch (escape) {- case 'b':- reusableBuffer.append('\b');- break;- case 'f':- reusableBuffer.append('\f');- break;- case 'n':- reusableBuffer.append('\n');- break;- case 'r':- reusableBuffer.append('\r');- break;- case 't':- reusableBuffer.append('\t');- break;- case '"':- case '/':- case '\\':- reusableBuffer.append(escape);- break;- case 'u':- int escaped = 0;-- for (int j = 0; j < 4; j++) {- escaped <<= 4;- int digit = buffer[index++];- if (digit >= '0' && digit <= '9') {- escaped |= (digit - '0');- } else if (digit >= 'A' && digit <= 'F') {- escaped |= (digit - 'A') + 10;- } else if (digit >= 'a' && digit <= 'f') {- escaped |= (digit - 'a') + 10;- } else {- throw createParseException(null, "Expected unicode hex escape character: "- + (char)digit + " (" + digit + ")", false);- }- }-- reusableBuffer.append((char)escaped);- break;- default:- throw createParseException(null, "Invalid escape: \\" + escape, false);- }- break;- default:- reusableBuffer.append(c);- }- }-- if (index > bufferLength) {- index = bufferLength; // Reset index to last valid location- throw createParseException(null, "EOF encountered in the middle of a string escape", false);- }- }- }-- @SuppressWarnings("fallthrough")- private void consumeTokenStringUtf8Char(char c) throws JsonParserException {- ensureBuffer(5);-- // Hand-UTF8-decoding- switch (c & 0xf0) {- case 0x80:- case 0x90:- case 0xa0:- case 0xb0:- throw createParseException(null,- "Illegal UTF-8 continuation byte: 0x" + Integer.toHexString(c & 0xff), false);- case 0xc0:- // Check for illegal C0 and C1 bytes- if ((c & 0xe) == 0)- throw createParseException(null, "Illegal UTF-8 byte: 0x" + Integer.toHexString(c & 0xff),- false);- // fall-through- case 0xd0:- c = (char)((c & 0x1f) << 6 | (buffer[index++] & 0x3f));- reusableBuffer.append(c);- utf8adjust++;- break;- case 0xe0:- c = (char)((c & 0x0f) << 12 | (buffer[index++] & 0x3f) << 6 | (buffer[index++] & 0x3f));- utf8adjust += 2;- // Check for illegally-encoded surrogate - http://unicode.org/faq/utf_bom.html#utf8-4- if ((c >= '\ud800' && c <= '\udbff') || (c >= '\udc00' && c <= '\udfff'))- throw createParseException(null, "Illegal UTF-8 codepoint: 0x" + Integer.toHexString(c),- false);- reusableBuffer.append(c);- break;- case 0xf0:- if ((c & 0xf) >= 5)- throw createParseException(null, "Illegal UTF-8 byte: 0x" + Integer.toHexString(c & 0xff),- false);-- // Extended char- switch ((c & 0xc) >> 2) {- case 0:- case 1:- reusableBuffer.appendCodePoint((c & 7) << 18 | (buffer[index++] & 0x3f) << 12- | (buffer[index++] & 0x3f) << 6 | (buffer[index++] & 0x3f));- utf8adjust += 3;- break;- case 2:- // TODO: \uFFFD (replacement char)- int codepoint = (c & 3) << 24 | (buffer[index++] & 0x3f) << 18 | (buffer[index++] & 0x3f) << 12- | (buffer[index++] & 0x3f) << 6 | (buffer[index++] & 0x3f);- throw createParseException(null,- "Unable to represent codepoint 0x" + Integer.toHexString(codepoint)- + " in a Java string", false);- case 3:- codepoint = (c & 1) << 30 | (buffer[index++] & 0x3f) << 24 | (buffer[index++] & 0x3f) << 18- | (buffer[index++] & 0x3f) << 12 | (buffer[index++] & 0x3f) << 6- | (buffer[index++] & 0x3f);- throw createParseException(null,- "Unable to represent codepoint 0x" + Integer.toHexString(codepoint)- + " in a Java string", false);- default:- assert false : "Impossible";- }- break;- default:- // Regular old byte- break;- }- if (index > bufferLength)- throw createParseException(null, "UTF-8 codepoint was truncated", false);- }-- /**- * Advances a character, throwing if it is illegal in the context of a JSON string.- */- private char stringChar() throws JsonParserException {- char c = buffer[index++];- if (c < 32)- throwControlCharacterException(c);- return c;- }-- private void throwControlCharacterException(char c) throws JsonParserException {- // Need to ensure that we position this at the correct location for the error- if (c == '\n') {- linePos++;- rowPos = index + 1 + charOffset;- utf8adjust = 0;- }- throw createParseException(null,- "Strings may not contain control characters: 0x" + Integer.toString(c, 16), false);- }-- /**- * Quick test for digit characters.- */- private boolean isDigitCharacter(int c) {- return (c >= '0' && c <= '9') || c == 'e' || c == 'E' || c == '.' || c == '+' || c == '-';- }-- /**- * Quick test for whitespace characters.- */- boolean isWhitespace(int c) {- return c == ' ' || c == '\n' || c == '\r' || c == '\t';- }-- /**- * Quick test for ASCII letter characters.- */- boolean isAsciiLetter(int c) {- return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');- }-- /**- * Returns true if EOF.- */- private boolean refillBuffer() throws JsonParserException {- try {- int r = reader.read(buffer, 0, buffer.length);- if (r <= 0) {- return true;- }- charOffset += bufferLength;- index = 0;- bufferLength = r;- return false;- } catch (IOException e) {- throw createParseException(e, "IOException", true);- }- }-- /**- * Peek one char ahead, don't advance, returns {@code EOF} (-1) on end of input.- */- private int peekChar() {- return eof ? -1 : buffer[index];- }-- /**- * Ensures that there is enough room in the buffer to directly access the next N chars via buffer[].- */- int ensureBuffer(int n) throws JsonParserException {- // We're good here- if (bufferLength - n >= index) {- return n;- }-- // Nope, we need to read more, but we also have to retain whatever buffer we have- if (index > 0) {- charOffset += index;- bufferLength = bufferLength - index;- System.arraycopy(buffer, index, buffer, 0, bufferLength);- index = 0;- }- try {- while (buffer.length > bufferLength) {- int r = reader.read(buffer, bufferLength, buffer.length - bufferLength);- if (r <= 0) {- return bufferLength - index;- }- bufferLength += r;- if (bufferLength > n)- return bufferLength - index;- }-- // Should be impossible- assert false : "Unexpected internal error";- throw new IOException("Unexpected internal error");- } catch (IOException e) {- throw createParseException(e, "IOException", true);- }- }-- /**- * Advance one character ahead, or return {@code EOF} (-1) on end of input.- */- private int advanceChar() throws JsonParserException {- if (eof)- return -1;-- int c = buffer[index];- if (c == '\n') {- linePos++;- rowPos = index + 1 + charOffset;- utf8adjust = 0;- }-- index++;-- // Prepare for next read- if (index >= bufferLength)- eof = refillBuffer();-- return c;- }- - int advanceCharFast() {- int c = buffer[index];- if (c == '\n') {- linePos++;- rowPos = index + 1 + charOffset;- utf8adjust = 0;- }-- index++;- return c;- }- - private void consumeWhitespace() throws JsonParserException {- int n;- do {- n = ensureBuffer(BUFFER_ROOM);- for (int i = 0; i < n; i++) {- char c = buffer[index];- if (!isWhitespace(c)) {- fixupAfterRawBufferRead();- return;- }- if (c == '\n') {- linePos++;- rowPos = index + 1 + charOffset;- utf8adjust = 0;- }- index++;- }- } while (n > 0);- eof = true;- }- - /**- * Consumes a token, first eating up any whitespace ahead of it. Note that number tokens are not necessarily valid- * numbers.- */- int advanceToToken(boolean allowSemiString) throws JsonParserException {- int c = advanceChar();- while (isWhitespace(c))- c = advanceChar();-- tokenCharPos = index + charOffset - rowPos - utf8adjust;- tokenCharOffset = charOffset + index;-- int oldIndex = index;- int token;- switch (c) {- case -1:- return TOKEN_EOF;- case '[':- token = TOKEN_ARRAY_START;- break;- case ']':- token = TOKEN_ARRAY_END;- break;- case ',':- token = TOKEN_COMMA;- break;- case ':':- token = TOKEN_COLON;- break;- case '{':- token = TOKEN_OBJECT_START;- break;- case '}':- token = TOKEN_OBJECT_END;- break;- case 't':- try {- consumeKeyword((char) c, JsonTokener.TRUE);- token = TOKEN_TRUE;- } catch (JsonParserException e) {- if (allowSemiString) {- index = oldIndex - 1;- consumeTokenSemiString();- token = TOKEN_SEMI_STRING;- } else throw e;- }- break;- case 'f':- try {- consumeKeyword((char)c, JsonTokener.FALSE);- token = TOKEN_FALSE;- } catch (JsonParserException e) {- if (allowSemiString) {- index = oldIndex - 1;- consumeTokenSemiString();- token = TOKEN_SEMI_STRING;- } else throw e;- }- break;- case 'n':- try {- consumeKeyword((char)c, JsonTokener.NULL);- token = TOKEN_NULL;- } catch (JsonParserException e) {- if (allowSemiString) {- index = oldIndex - 1;- consumeTokenSemiString();- token = TOKEN_SEMI_STRING;- } else throw e;- }- break;- case '"':- case '\'':- consumeTokenString(c);- token = TOKEN_STRING;- break;- case '-':- case '0':- case '1':- case '2':- case '3':- case '4':- case '5':- case '6':- case '7':- case '8':- case '9':- consumeTokenNumber((char)c);- token = TOKEN_NUMBER;- break;- case '+':- case '.':- throw createParseException(null, "Numbers may not start with '" + (char)c + "'", true);- default:- if (allowSemiString) {- index--;- consumeTokenSemiString();- token = TOKEN_SEMI_STRING;- break;- } else {- if (isAsciiLetter(c))- throw createHelpfulException((char)c, null, 0);-- throw createParseException(null, "Unexpected character: " + (char)c, true);- }- }- -// consumeWhitespace();- return token;- }-- int tokenChar() throws JsonParserException {- int c = advanceChar();- while (isWhitespace(c))- c = advanceChar();- return c;- }-- /**- * Helper function to fixup eof after reading buffer directly.- */- void fixupAfterRawBufferRead() throws JsonParserException {- if (index >= bufferLength)- eof = refillBuffer();- }-- /**- * Throws a helpful exception based on the current alphanumeric token.- */- JsonParserException createHelpfulException(char first, char[] expected, int failurePosition)- throws JsonParserException {- // Build the first part of the token- StringBuilder errorToken = new StringBuilder(first- + (expected == null ? "" : new String(expected, 0, failurePosition)));-- // Consume the whole pseudo-token to make a better error message- while (isAsciiLetter(peekChar()) && errorToken.length() < 15)- errorToken.append((char)advanceChar());-- return createParseException(null, "Unexpected token '" + errorToken + "'"- + (expected == null ? "" : ". Did you mean '" + first + new String(expected) + "'?"), true);- }-- /**- * Creates a {@link JsonParserException} and fills it from the current line and char position.- */- JsonPa
Diff truncated.