MCPcopy Create free account
hub / github.com/bazelbuild/bazel / encode

Method encode

src/main/java/net/starlark/java/lib/json/Json.java:142–256  ·  view source on GitHub ↗
(Object x)

Source from the content-addressed store, hash-verified

140 }
141
142 private void encode(Object x) throws EvalException, InterruptedException {
143 if (x instanceof Encodable) {
144 x = ((Encodable) x).objectForEncoding(semantics);
145 }
146
147 if (x == Starlark.NONE) {
148 out.append("null");
149 return;
150 }
151
152 if (x instanceof String s) {
153 appendQuoted(s);
154 return;
155 }
156
157 if (x instanceof Boolean || x instanceof StarlarkInt) {
158 out.append(x);
159 return;
160 }
161
162 if (x instanceof StarlarkFloat fl) {
163 if (!Double.isFinite(fl.toDouble())) {
164 throw Starlark.errorf("cannot encode non-finite float %s", x);
165 }
166 out.append(x.toString()); // always contains a decimal point or exponent
167 return;
168 }
169
170 // e.g. dict (must have string keys)
171 if (x instanceof Map<?, ?> m) {
172 // Sort keys for determinism.
173 Object[] keys = m.keySet().toArray();
174 for (Object key : keys) {
175 if (!(key instanceof String)) {
176 throw Starlark.errorf(
177 "%s has %s key, want string", Starlark.type(x), Starlark.type(key));
178 }
179 }
180 Arrays.sort(keys);
181
182 // emit object
183 out.append('{');
184 String sep = "";
185 for (Object key : keys) {
186 out.append(sep);
187 sep = ",";
188 appendQuoted((String) key);
189 out.append(':');
190 try {
191 encode(m.get(key));
192 } catch (EvalException ex) {
193 throw Starlark.errorf(
194 "in %s key %s: %s", Starlark.type(x), Starlark.repr(key), ex.getMessage());
195 }
196 }
197 out.append('}');
198 return;
199 }

Callers 1

encodeMethod · 0.95

Calls 14

appendQuotedMethod · 0.95
errorfMethod · 0.95
typeMethod · 0.95
reprMethod · 0.95
dirMethod · 0.95
getattrMethod · 0.95
objectForEncodingMethod · 0.80
getMethod · 0.65
appendMethod · 0.45
toDoubleMethod · 0.45
toStringMethod · 0.45
toArrayMethod · 0.45

Tested by

no test coverage detected