Track Decode Positions With InputOffset
Read Decoder.InputOffset after a failed decode to learn how far the stream was consumed, then slice the original document around that byte offset.
Page 18 of 50
Read Decoder.InputOffset after a failed decode to learn how far the stream was consumed, then slice the original document around that byte offset.
Format JSON for humans or machines with MarshalIndent and Compact: pretty output takes a custom prefix, and Compact squeezes it back to one line.
Validate JSON syntax with json.Valid before decoding: trailing commas fail the gate, so bad payloads are rejected without half-filled structs.
Snapshot and merge map data with maps.Clone, maps.Copy, and maps.Equal: clone isolates edits, Copy overwrites shared keys, Equal compares pairs exactly.
Turn Content-Type style strings into a canonical type plus a parameter map with mime.ParseMediaType, so malformed values fail instead of being guessed.
Compare math.Mod and math.Remainder on the same operands: truncated division keeps the dividend sign, IEEE 754 remainder rounds to the nearest quotient.
Register a deferred cleanup and call os.Exit to prove the deferred function never runs: exit terminates the process immediately.
Interpolate variables in config templates with os.Expand and a resolver callback, or os.ExpandEnv when missing variables should expand to empty strings.
Handle small files with os.ReadFile, os.WriteFile, and os.Stat: one call each for write, read, and metadata, with IsNotExist classifying missing paths.
Parse Go source text into a syntax tree with go/parser, then walk it with ast.Inspect to report every function declaration and its parameter count.
Escape arbitrary strings into safe ASCII literals with strconv.Quote and QuoteToASCII, keeping control bytes and non-ASCII visible in logs.
Obtain reflect.Type without allocating a zero value using reflect.TypeFor, then compare types across interfaces and generics-driven code paths.
Filter a slice into its own backing array with s[:0] and append, then prove the aliasing by reading the stale tail beyond the truncated length.
Trim a slice back to its length with slices.Clip so unused backing capacity cannot be appended into, and watch the next append allocate fresh storage.
Order two slices element by element with slices.Compare and CompareFunc: -1, 0, or 1 falls out of a lexicographic walk.
Probe slices with Contains, Index, and Equal: presence checks compare by ==, Index returns the first match or -1, and Equal treats nil as empty.
Check ordering invariants with slices.IsSorted and IsSortedFunc before binary searching, so unsorted input is caught instead of producing wrong results.
Give the slog handler a LevelVar as its threshold so the minimum level can be raised or lowered while the process runs, with no logger rebuild.
Locate insertion points in sorted data with sort.Search: it returns the first index whose predicate turns true, or the slice length when nothing matches.
Send progress and warnings to os.Stderr while result rows stay on stdout, so redirection and pipes capture clean data only.
Assemble text with strings.Builder: appends write into one internal buffer, Grow preallocates capacity, and Reset empties content while keeping the buffer.
Parse host:port and key=value pairs with strings.Cut, which splits at the first separator and reports before, after, and whether a separator was found.
Strip leading characters correctly: strings.TrimLeft removes any leading cutset runes, TrimPrefix removes one exact prefix, and confusing them corrupts data.
Wake every parked goroutine at once with sync.Cond Broadcast: Signal releases a single waiter while Broadcast releases all of them.
Depend on the sync.Locker interface so helpers accept any lock: Mutex directly and RWMutex through RLocker().
CompareAndSwap and CompareAndDelete only write or delete when the stored value still matches, so concurrent updates cannot silently overwrite each other.
Run a fallible initializer exactly once across concurrent callers with sync.OnceValues, so every caller receives the same value or the same error.
Format timestamps with Go's reference layout: the fixed template 2006-01-02 15:04:05 encodes each element, and Parse reuses the same layout in reverse.
Build time instants from epoch seconds with time.Unix and split them back with Unix, UnixMilli, and UnixMicro for round trips.
Build query strings with url.Values: Encode percent-escapes values and sorts keys deterministically, while ParseQuery decodes raw query strings back.
Open an in-memory zip with zip.NewReader and read each entry via FileHeader metadata plus f.Open, so archive contents are inspected without touching disk.
Render readable report tables from a plain CLI with String.repeat rules and printf column widths, staying inside the standard library.
Swap a stack head with compareAndSet in a retry loop: the update succeeds only when no other thread moved the reference between read and write.
Update individual array elements with compareAndSet retry loops so several threads can bump counters in one array without locking the whole.
Move up to maxElements items out of a BlockingQueue in one locked step with drainTo, so consumer batches stay efficient and never race producers.
Timed offer and poll give up after the timeout instead of blocking forever: a full queue returns false, an empty one null, and neither path throws.
BreakIterator.getCharacterInstance splits text into user-perceived grapheme clusters: a ZWJ-joined emoji family is one character despite many code points.
Convert identifiers between camelCase and snake_case: insert underscores before capitals in one direction, capitalize after them in the other.
Follow the CLI exit-code convention: zero for success, one for business failures, two for usage errors, with diagnostics written to stderr.
Hand-roll a minimal CLI parser: --key=value options land in a map, bare switches become true, and leftover arguments stay positional.
Create a hard link with Files.createLink so both names share one inode: writes via either path are visible to both and deleting one name keeps the data.
Split a CSV line with a tiny state machine so quoted fields keep their commas and doubled quotes decode into literal quotation marks.
Bridge java.util.Date and Calendar to java.time through Instant and toInstant so old APIs and new code exchange the same moment losslessly.
Sort doubles reliably with Double.compare: it treats NaN as largest and distinguishes -0.0 from 0.0, both of which break subtraction-based comparators.
Parse ISO-8601 duration text like PT2H45M30S into a Duration, extend it, read back hour/minute/second parts, and convert to a single unit.
Give each enum constant its own behavior via an abstract method in the enum body, overridden per constant, so a new command cannot miss its implementation.
Parse user-supplied tokens into enum constants with valueOf, trim and uppercase the input, and fail with the full list of valid constants.
Pull values out of delimited log fields with indexOf and substring instead of regex, and return null for missing keys so callers decide what absence means.
Detect upload MIME types with Files.probeContentType and treat the null result as unknown, since the mapping comes from the system file-type table.
Wrap a Callable in FutureTask so the expensive work runs exactly once even when several threads block on get, and later callers reuse the cached result.
Send a blocking HTTP request with HttpClient.send and inspect status code, headers, and body length, the sync counterpart to the async chaining API.
Integer.decode reads 0x and # prefixes as hex and a leading 0 as octal, while parseInt accepts an explicit radix from 2 to 36 for everything else.
Escape a string for embedding in JSON: quotes, backslashes, and control characters become the two-character or \uXXXX forms the spec requires.
Lambdas may only capture locals that are never reassigned: the compiler rejects captured variables that change, so mutable state flows through containers.
Walk an ArrayList forward with next() and backward with previous() from the same cursor, and replace elements in place via set() during iteration.
Validate card-style numbers with the Luhn checksum: double every second digit from the right and require the total to be divisible by ten.
Count occurrences in one pass with Map.merge: the remapping function runs only when the key is already present, so a fresh key needs no null check.
Mask card numbers, emails, and phone numbers with repeat and substring so logs keep the shape of a value without exposing the sensitive parts.
Sort versioned names like backup-10 after backup-9 by comparing digit runs numerically instead of lexicographically with a Character.isDigit scan.
Objects.checkIndex and checkFromToIndex return their argument when bounds hold and throw IndexOutOfBoundsException with a precise message when they do not.
Tighten a secret file to owner read/write with PosixFilePermissions, probing filesystem support first so non-POSIX systems degrade cleanly.
Serve localized messages from code-only ListResourceBundle subclasses: getBundle resolves by locale and default-locale fallback stays disabled.
Turn arbitrary titles into URL-safe slugs: NFD normalization folds accented letters, then runs of non-alphanumerics collapse into single dashes.
Probe a TCP service with Socket connect timeout and setSoTimeout so a dead peer cannot hang the caller, using a local ServerSocket as the responder.
anyMatch, allMatch, and noneMatch stop consuming the stream at the first decisive element, and an empty stream answers true for all and none, false for any.
Edit text in place with StringBuilder insert, reverse, delete, and replace instead of building new String copies per concatenation step.
Stop a worker with a bounded Thread.join timeout, then escalate to interrupt and join again so shutdown cannot hang on a blocked thread.
Prune large subtrees during Files.walkFileTree by returning SKIP_SUBTREE from preVisitDirectory, so dependency caches and hidden files never enter the walk.
Break text into lines no wider than the limit with a greedy pass: fill each line with as many words as fit, then start the next line.
Parse an XML payload into a DOM tree with a hardened DocumentBuilderFactory that rejects DOCTYPE declarations, then read elements and attributes.
Extract uploaded archives safely: resolve every entry against the target directory, normalize it, and reject any path that escapes the folder.
Compare parsed data against expected structures with assert.deepStrictEqual, where object key order is ignored but array order matters.
Feed chunks into createHash with repeated update calls and compare the digest against a one-shot hash to prove hashing is incremental.
Draw bounded integers with crypto.randomInt, where the upper bound is exclusive, avoiding the modulo bias that hand-rolled Math.random tricks introduce.
Probe existence and read or write permission with fs.access and its F_OK, R_OK, and W_OK constants, catching ENOENT for missing paths.
Copy a directory tree with fs.cp using recursive and filter options, skipping scratch files while preserving the nested folder structure.
Match nested files with fs.glob patterns, where one star stays inside a single path segment, two stars cross directories, and classes narrow matches.
List a directory with withFileTypes to receive Dirent objects, classifying files and folders by name without extra stat calls per entry.
Publish new content with fs.rename so the destination is replaced in one filesystem operation and readers never observe a half-written file.
Read a path's size, timestamps, and entry kind with fs.stat, distinguishing files from directories before acting on the metadata.
Compare Map and plain-object lookup semantics: object keys stringify, Map keys keep identity, and size plus delete behave predictably for dynamic data.
Compose and decompose filesystem paths with join, resolve, basename, extname, and dirname so path logic never relies on string concatenation.
Stretch a password into a 256-bit key with WebCrypto PBKDF2 using a fixed salt and 100000 iterations, then render the derived bits as hex.
Read environment variables with string-aware defaults: coalesce missing vars, coerce numbers explicitly, and parse flag or list values safely.
Set process.exitCode instead of calling process.exit so buffered output drains first, and summarize batch checks into one exit status for shell scripts.
Validate names against suffix and prefix rules with endsWith and startsWith, handling extension allowlists and reserved-name prefixes.
Encrypt and decrypt with WebCrypto AES-GCM, seeing the 16-byte authentication tag and verifying that tampered ciphertext is rejected.
Print nested objects with util.inspect using depth, compact, and breakLength options so log lines stay single-line and deep structures stay readable.
Wrap terminal text with util.styleText; validateStream defaults to true so ANSI is emitted only when stdout can render colors; pass false to always wrap.
Compress UTF-8 text with gzipSync and restore it with gunzipSync, verifying the round trip is byte-identical and reporting the size reduction.
Diffing two snapshots with Sets answers which items arrived and which left, so change feeds and cache invalidation can react to exact deltas.
Array.of(7) builds a one-element array while new Array(7) reserves seven empty slots, and Array.of stays a generic factory when borrowed with call.
A concurrency-capped task queue gains pause() to hold new starts, resume() to continue them, and drain() that resolves once nothing runs or waits.
A fixed pool recycles connections: acquire resolves immediately or parks the caller FIFO, and release hands the resource to the longest-waiting job.
matches tests the element itself against a selector, closest walks up through ancestors from itself, and both return null when nothing matches.
animate() starts a Web Animation immediately, returning an Animation object whose playState, currentTime, and finished promise give full programmatic control.
Seven values are falsy while empty arrays and objects are truthy, so filter(Boolean) compacts lists and || versus ?? treat missing defaults differently.
for...in walks string keys including enumerable extras, for...of reads elements through the iterator protocol, and plain objects need Object.entries for of.
A label lets continue restart the outer loop and break leave both loops at once, where an unlabeled break only exits the innermost iteration.
??= writes only for nullish values, ||= for falsy ones and &&= for truthy ones, and the right-hand expression is skipped entirely when the guard fails.